如何仅分配或释放数组的一部分? [英] How allocate or free only parts of an array?
问题描述
看这个例子:
int *array = malloc (10 * sizeof(int))
有没有办法只释放前 3 个块?
Is there a way to free only the first 3 blocks?
或者有一个带有负索引的数组,或不以 0 开头的索引?
Or to have an array with negative indexes, or indexes that don't begin with 0?
推荐答案
您不能直接释放前 3 个块.您可以通过将数组重新分配更小来做类似的事情:
You can't directly free the first 3 blocks. You can do something similar by reallocating the array smaller:
/* Shift array entries to the left 3 spaces. Note the use of memmove
* and not memcpy since the areas overlap.
*/
memmove(array, array + 3, 7);
/* Reallocate memory. realloc will "probably" just shrink the previously
* allocated memory block, but it's allowed to allocate a new block of
* memory and free the old one if it so desires.
*/
int *new_array = realloc(array, 7 * sizeof(int));
if (new_array == NULL) {
perror("realloc");
exit(1);
}
/* Now array has only 7 items. */
array = new_array;
至于问题的第二部分,您可以增加 array
使其指向内存块的中间.然后您可以使用负索引:
As to the second part of your question, you can increment array
so it points into the middle of your memory block. You could then use negative indices:
array += 3;
int first_int = array[-3];
/* When finished remember to decrement and free. */
free(array - 3);
同样的想法也适用于相反的方向.您可以从 array
中减去以使起始索引大于 0.但要小心:正如@David Thornley 指出的那样,根据 ISO C 标准,这在技术上是无效的,并且可能不适用于所有平台.
The same idea works in the opposite direction as well. You can subtract from array
to make the starting index greater than 0. But be careful: as @David Thornley points out, this is technically invalid according to the ISO C standard and may not work on all platforms.
这篇关于如何仅分配或释放数组的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!