我做这段代码是为了读取数组,它在小测试(3x3(中正常工作,但我需要它来读取15x15的数组。150次扫描后,它停止工作,返回3221225477并关闭。发生了什么?如何修复?
int ** ler(){
FILE *a;
a = fopen("matriz.txt", "r");
int **N;
int b, c, d;
N = malloc(15 * sizeof(int));
for (b = 0; b < 15; b++){
N[b] = malloc(15 * sizeof(int));
}
for (b = 0; b < 15; b++){
for (c = 0; c < 15; c++){
fscanf(a, "%i", &d);
N[b][c] = d;
}
}
return N;
}
至少这个问题:
错误的大小分配
int **N; // vvvvvvvvvvv This is the size of an int
//N = malloc(15 * sizeof(int));
N = malloc(15 * sizeof *N);
// ^^^^^^^^^ The size of a pointer is needed here
使用OP的代码,当int
<int *
的大小,则分配被缩小。
避免这种错误,使用*N
进行编码,而不是尝试匹配类型。
// Nice idiom
ptr = malloc(sizeof *ptr * n);
// ^^^^^^^^^^^ The right size regardless of what `ptr` pointers to.
阅读完毕后,请致电fclose(a)
。