我的动态二维数组有问题。
使用 malloc
就可以了。使用realloc
,它失败了。
这不起作用:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *const *argv) {
unsigned ** gmatrix = NULL;
int cap = 4;
/*
...
*/
gmatrix = realloc(gmatrix, 4 * sizeof(unsigned*));
for(unsigned i = 0; i < cap; i++) {
gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
}
// initialize:
for(unsigned i = 0; i < cap; i++) {
for(unsigned j = 0; j < cap; j++) {
gmatrix[i][j] = 0;
}
}
}
但这确实:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *const *argv) {
unsigned ** gmatrix = NULL;
int cap = 4;
/*
...
*/
gmatrix = malloc(cap * sizeof(unsigned*));
for(unsigned i = 0; i < cap; i++) {
gmatrix[i] = malloc(cap* sizeof(unsigned));
}
for(unsigned i = 0; i < cap; i++) {
for(unsigned j = 0; j < cap; j++) {
gmatrix[i][j] = 0;
}
}
}
在第一个代码部分中,我收到段错误错误。为什么?
最佳答案
gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
应该是
gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));
使用gmatrix
而不是gmatrix[i]
将导致Undefined Behavior您遇到的段错误是 Undefined Behavior 的副作用之一.
编辑:
您应该在第一个 malloc
之后将 gmatrix[i]
初始化为 NULL
,如 @MattMcNabb pointed out 。因此,在第一次调用 realloc
后使用以下内容:
for(unsigned i = 0; i < cap; i++) {
gmatrix[i] = NULL;
gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));
}
关于c - 使用 realloc 的动态二维数组会出现段错误,但可以与 malloc 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555169/