为什么扫描停止工作(使用内存分配)?
Why the scan stopped working (using memory allocation)?
我已经完成了这段代码来读取一个数组,它在小型测试 (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)
。
我已经完成了这段代码来读取一个数组,它在小型测试 (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)
。