gpt4 book ai didi

fscanf 的 C 段错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:12 26 4
gpt4 key购买 nike

尝试使用 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];

nm 在您声明二维数组 max初始化。尝试在 int max[m][n]; 之前打印 nm 等,你会发现它们包含垃圾值。

因此,Undefined Behavior 就是您遇到的情况,因为您无法真正判断数组的大小。

改成这样:

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];

现在,当您创建数组时,nm 将使用从文件中读取的值进行初始化。


如果你想在阅读nm之前声明你的数组,那么你应该使用指针,阅读nm 然后是 dynamically allocate the arrays .

关于fscanf 的 C 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com