【发布时间】:2016-04-06 16:27:30
【问题描述】:
尝试使用 fscanf 读取输入的 .txt 文件,并将行内容存储到 int 变量、数组和 2D 数组中,以便稍后使用该值进行计算。我认为这里的问题是因为我没有使用 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 max[m][n], allo[m][n], need[n][m];...m和n尚未初始化,因此它是未定义的行为。除此之外,当您更改定义它们的变量时,VLA 不会自行调整大小。我还注意到m和n被转换为need[n][m]。 -
请不要更改问题来尝试解决问题。在您自己的办公桌上执行此操作,否则会使对话看起来无关紧要。