为什么我不能重新分配一个已经完全初始化的数组?
Why can't I realloc an array that was fully initialized?
看看下面的这段代码。当我通过 mallocating space 创建一个数组时,我总是可以调整数组的大小而不会丢失数据。但是,当我通过使用 int test2[] = {3};
完全初始化它来创建数组时,我无法 重新分配 。这是为什么?这只是一个愚蠢的例子,但它很好地展示了我面临的问题。
我尝试以不同的方式(*、&、** 等)引用 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 循环后的代码时,程序编译并正常执行。
声明int test2[] = {3};
不会创建稍后可以释放或重新分配的内存!相反,它定义了一个 fixed 长度的数组,很可能 'created' 在 堆栈 上.
另一方面,对 malloc
的调用会从 堆 中分配请求的内存量(本质上,一个大的内存池可供您的 运行 程序);此内存 'chunk' 稍后可以使用 realloc
重新调整大小,并且 必须 通过调用 free
释放(当您使用完它时)。
看看下面的这段代码。当我通过 mallocating space 创建一个数组时,我总是可以调整数组的大小而不会丢失数据。但是,当我通过使用 int test2[] = {3};
完全初始化它来创建数组时,我无法 重新分配 。这是为什么?这只是一个愚蠢的例子,但它很好地展示了我面临的问题。
我尝试以不同的方式(*、&、** 等)引用 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 循环后的代码时,程序编译并正常执行。
声明int test2[] = {3};
不会创建稍后可以释放或重新分配的内存!相反,它定义了一个 fixed 长度的数组,很可能 'created' 在 堆栈 上.
另一方面,对 malloc
的调用会从 堆 中分配请求的内存量(本质上,一个大的内存池可供您的 运行 程序);此内存 'chunk' 稍后可以使用 realloc
重新调整大小,并且 必须 通过调用 free
释放(当您使用完它时)。