我的目标是在 C 中为二维 int 数组动态重新分配内存。我知道已经有几个关于该主题的问题,但不幸的是我的代码无法正常运行,我不知道出了什么问题。
首先我分配内存:
int n = 10;
int m = 4;
int** twoDimArray;
twoDimArray = (int**)malloc(n * sizeof(int*));
for(int i = 0; i < n; i++) {
twoDimArray[i] = (int*)malloc(m * sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)
并用整数初始化数组:
for(int i = 0; i < n; i++) {
for(j = 0; j < 4; j++) {
twoDimArray[i][j] = i * j;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我用来realloc()动态重新分配内存:
int plus = 10;
int newArraySize = n + plus;
twoDimArray = (int**)realloc(twoDimArray, newArraySize * sizeof(int));
Run Code Online (Sandbox Code Playgroud)
我希望twoDimArray现在可以在 [10][0] 访问我的数组,但是在运行时
printf("twoDimArray[10][0] = %d\n", twoDimArray[10][0]);
Run Code Online (Sandbox Code Playgroud)
我收到“EXC_BAD_ACCESS”运行时错误。
也许我错过了一些相当简单的东西,但因为我是 C 新手,无法找出我的错误。任何帮助表示赞赏。
重新分配指针数组是必要的,但是这样您就只有n指向有效值的值。您需要分配其余的子数组,因为新分配的内存指向未分配/无效的区域。该错误不是来自访问指针,而是来自取消引用它。
您需要添加类似以下内容:
for(int i = n; i < n+plus; i++) {
twoDimArray[i] = malloc(m * sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)
(释放也是如此:首先在循环中释放数组,然后释放指针数组)
在旁边:
realloc直接分配给原始变量可能会出现问题。即使在调整大小的情况下很少见(在什么情况下 malloc 返回 NULL?),您也应该将结果复制到临时变量中,检查, 以及旧指针(如果重新分配失败)。reallocNULLNULLfree