[英]C Segmentation fault with fscanf
尝试使用 fscanf 读取输入的 .txt 文件,并将行内容存储到 int 变量、数组和二维数组中,以便稍后使用该值进行计算。 我认为这里的问题是因为我没有使用 fscanf 处理“EOF”?
这是我的代码:
int main(){
FILE *fp;
int n; // # resources
int m; // # processes
int avail[n];
int max[m][n], allo[m][n];
char temp1[10];
fp = fopen("test.txt", "r");
if (fp == NULL){
exit(EXIT_FAILURE);
}
fscanf(fp, "%d %d", &n, &m);
printf("%d %d", n, m);
printf("\n");
// Store the second line content to allo[]
for(int i = 0; i < n; i++){
fscanf(fp, "%s", temp1);
avail[i] = atoi(temp1);
printf("%d ", avail[i]);
}
printf("\n");
// Store the line3-7 content to 2D max[][]
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
fscanf(fp, "%s", temp1);
max[i][j] = atoi(temp1);
printf("%d ", max[i][j]);
}
printf("\n");
}
// Store the line8-12 content to 2D allo
for(int i = 0; i < m; i++){
for(int j = 0; i < n; j++){
fscanf(fp, "%s", temp1);
allo[i][j] = atoi(temp1);
printf("%d ", allo[i][j]);
}
printf("\n");
}
fclose(fp);
return 0;
}
这是 .txt 输入文件:
3 5
9 6 3
5 5 2
4 1 3
8 3 4
5 4 2
4 4 3
0 1 0
1 1 0
1 0 2
0 0 1
1 2 2
这是输出:
3 5
9 6 3
5 5 2
4 1 3
8 3 4
5 4 2
4 4 3
Segmentation fault: 11
问题在这里:
int n; // # resources
int m; // # processes
int avail[n];
int max[m][n], allo[m][n], need[n][m];
当您声明二维数组max
时, n
和m
未初始化。 尝试在int max[m][n];
之前打印n
和m
int max[m][n];
等,你会看到它们包含垃圾值。
因此,您正在经历未定义行为,因为您无法真正判断数组的大小。
改成这样:
int n; // # resources
int m; // # processes
fscanf(fp, "%d %d", &n, &m);
printf("%d %d", n, m);
int avail[n];
int max[m][n], allo[m][n], need[n][m];
现在,当您创建数组时, n
和m
将使用从文件中读取的值进行初始化。
如果你想在读取n
和m
之前声明你的数组,那么你应该使用指针,读取n
和m
然后动态分配数组。
您声明int max[m][n], allo[m][n], need[n][m]
而m
和n
尚未设置,因此它们的大小未知。 设置大小后,它们不会自行调整大小。 所以写这些会给你“未定义的行为”
由于 m,n 在文件顶部声明数组时未初始化:
int avail[n];
int max[m][n], allo[m][n], need[n][m];
正如@WeatherVane 在评论中所述,您将获得未定义的行为。 也许您正在覆盖程序内存的其他部分(谁知道它是未定义的!)。
如果您需要创建动态数组,您应该执行以下操作:
int* avail;
...
fscanf(fp, "%d %d", &n, &m);
avail = (int*)malloc(n*sizeof(int));
当您初始化 max、allo 和需要时。 n 和 m 的值没有定义。
您可以将max
、 allo
和need
定义为int**
。
扫描 n 和 m 的值后,您可以调用以下函数为上述二维数组分配内存。
int ** get2DintArray(int r, int c){
int **arr = (int **)malloc(r * sizeof(int *));
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
return arr;
}
为了。 例如:-
allo = get2DintArray(m,n);
need = get2DintArray(n,m);
这种方法对于更高的 n 和 m 值很方便,其中堆栈内存可能不够用,因为在这种情况下您使用的是堆内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.