【发布时间】:2019-12-12 22:26:49
【问题描述】:
看看下面的代码。当我通过 malloc 为其分配空间来创建数组时,我总是可以调整数组的大小而不会丢失数据。但是当我通过使用int test2[] = {3}; 完全初始化它来创建一个数组时,我无法realloc。这是为什么?这只是一个愚蠢的例子,但它很好地展示了我面临的问题。
我尝试以不同的方式(*、&、** 等)引用 test2,但在某些时候,我发现自己只是希望能神奇地找到解决方案,而不知道自己在做什么。
我一直在谷歌上搜索,但我似乎找不到对此的正确解释或有效的解决方案。
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int *test1 = malloc(1 * sizeof(int));
test1[0] = 1;
test1 = realloc(test1, 2 * sizeof(int));
test1[1] = 2;
for(int i = 0; i < 2; i++)
{
printf("%d\n", test1[i]);
}
int test2[] = {3};
test2 = realloc(test2, 2 * sizeof(int));
test2[1] = 4;
for(int i = 0; i < 2; i++)
{
printf("%d\n", test2[i]);
}
}
输出:
test.c: In function 'main':
test.c:17:8: error: assignment to expression with array type
test2 = realloc(test2, 2 * sizeof(int));
当我在第一个 for 循环之后删除代码时,程序编译并正常执行。
【问题讨论】:
-
在
test2 = realloc(test2, 2 * sizeof(int));你不能重新分配一个数组。请检查内存分配函数的返回值。您只能传递从malloc或calloc(或者是NULL)获得的指向realloc的指针。