如何分配或数组免费仅部分? [英] How allocate or free only parts of an array?
问题描述
看到这样的例子:
int *array = malloc (10 * sizeof(int))
然后免费仅第3块?
Then free only the first 3 blocks?
或者等于做java的,有负面的指标,或者说不是始于索引0的数组。
Or make equal java, have an array with negative index, or an index that not began 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;
至于你问题的第二部分,你可以增加阵列
使其指向到你的内存块的中间。然后,您可以使用负的索引:
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);
同样的想法在相反方向工作的为好。您可以从阵列
减去使起始指数大于0但要注意:作为@大卫索恩利指出,这在技术上是无效的根据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屋!