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

dri*_*ker 3 c arrays

看这个例子:

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标准,这在技术上是无效的,并且可能无法在所有平台上运行.


Car*_*rum 5

你无法释放数组的一部分 - 你只能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程序员中,这种有趣的业务通常是不受欢迎的.

  • @Steve,David说的是对的.未定义指向已分配内存的外部,除了允许的结尾之外的内存.你甚至不必取消引用指针. (4认同)
  • `array - = 2;`是未定义的行为,IIRC,因为它形成一个指针值,既不指向有效内存也不是一个有效内存结束的指针.这通常不是现代计算机的问题,但有些系统(如旧的Boehm保守垃圾收集器)会遇到问题. (3认同)
  • @David-Boehm保守的垃圾收集器在很多方面都有问题。使用它的任何人都将调整其习惯用法以适合自己,但这并不意味着每个人都必须这样做。GC不是标准C语言的一部分。指针算术是C语言中的日常工作-当指针指向不存在的对象时取消引用是显而易见的未定义行为,而只是在某个地方存储了超出范围的指针?如果那是不确定的行为,我会感到惊讶。 (2认同)
  • @ Steve314:有很多这样的“为什么这种不确定的行为到底是什么?” 问题,可以帮助我们想象一个仅可以将有效值加载到寄存器的体系结构。该标准讨论“陷阱表示”,这意味着内存中的位模式(如果使用)会导致未定义的行为。您不会再希望整数和指针了,但是您可能会想到浮点数。相同的原则激发了“ array-2”是未定义行为的想法-C旨在允许在指针寄存器实际上无法保存无效指针的体系结构上实现。 (2认同)