看这个例子:
int *array = malloc (10 * sizeof(int))
Run Code Online (Sandbox Code Playgroud)
然后只释放前3个街区?
或者制作相同的java,使用具有负索引的数组,或者不以0开头的索引.
非常感谢.
Joh*_*ica 19
你不能直接释放前3个街区.你可以通过重新分配较小的数组来做类似的事情:
/* 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;
Run Code Online (Sandbox Code Playgroud)
至于你问题的第二部分,你可以增加array它,使它指向你的记忆块的中间.然后你可以使用负指数:
array += 3;
int first_int = array[-3];
/* When finished remember to decrement and free. */
free(array - 3);
Run Code Online (Sandbox Code Playgroud)
同样的想法也在相反的方向.您可以减去array以使起始索引大于0.但要小心:正如@David Thornley指出的那样,根据ISO C标准,这在技术上是无效的,并且可能无法在所有平台上运行.
你无法释放数组的一部分 - 你只能free()得到一个指针,malloc()当你这样做时,你将释放你所要求的所有分配.
对于负数或非零指数,当您从指针返回时,您可以使用指针执行任何操作malloc().例如:
int *array = malloc(10 * sizeof(int));
array -= 2;
Run Code Online (Sandbox Code Playgroud)
生成具有有效索引2-11的数组.对于负面指数:
int *array = malloc(10 * sizeof(int));
array += 10;
Run Code Online (Sandbox Code Playgroud)
现在,您可以访问此阵一样array[-1],array[-4]等等.
请确保不要访问阵列外部的内存.在C程序和C程序员中,这种有趣的业务通常是不受欢迎的.