如何分配或释放数组的部分?

看这个例子:

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

然后只释放前3个街区?

或者制作相同的java,具有负索引的数组,或者不以0开头的索引。

非常感谢。

你不能直接释放前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; 

至于问题的第二部分,你可以增加array ,使其指向内存块的中间位置。 然后你可以使用负指数:

 array += 3; int first_int = array[-3]; /* When finished remember to decrement and free. */ free(array - 3); 

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

你不能释放数组的一部分 – 你只能free()你从malloc()得到的指针,当你这样做时,你将释放你所要求的所有分配。

对于负数或非零指数,当您从malloc()获取指针时,可以使用指针执行任何操作。 例如:

 int *array = malloc(10 * sizeof(int)); array -= 2; 

生成具有有效索引2-11的数组。 对于负面指数:

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

现在您可以访问此数组,如array[-1]array[-4]等。

请确保不要访问arrays外的内存。 在C程序和C程序员中,这种有趣的业务通常是不受欢迎的。