gpt4 book ai didi

c - 如何仅分配或释放数组的一部分?

转载 作者:行者123 更新时间:2023-12-03 15:06:41 25 4
gpt4 key购买 nike

看这个例子:

int *array = malloc (10 * sizeof(int))

有没有办法只释放前 3 个 block ?

或者有一个带有负索引的数组,或者不以 0 开头的索引?

最佳答案

您不能直接释放前 3 个 block 。您可以通过重新分配更小的数组来做类似的事情:

/* 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所以它指向你的内存块的中间。然后,您可以使用负索引:
array += 3;
int first_int = array[-3];

/* When finished remember to decrement and free. */
free(array - 3);

同样的想法也适用于相反的方向。您可以从 array 中减去使起始索引大于 0。但要小心:正如@David Thornley 指出的那样,根据 ISO C 标准,这在技术上是无效的,并且可能不适用于所有平台。

关于c - 如何仅分配或释放数组的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2479766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com