Der Versuch, eine Eingabe-TXT-Datei mit fscanf zu lesen und den Zeileninhalt in der int-Variablen, dem Array und dem 2D-Array zu speichern, damit ich den Wert später für die Berechnung verwenden kann. Ich denke, das Problem hier ist, weil ich das "EOF" nicht mit fscanf behandelt habe?C Segmentierungsfehler mit fscanf
Hier ist mein Code:
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;
}
Hier ist die .txt-Eingabedatei:
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
Und hier ist der Ausgang:
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], müssen [n] [m];' ... 'm' und' n' nicht initialisiert worden ist, so ist es * undefined Verhalten*. Abgesehen davon ändern sich die VLAs nicht selbst, wenn Sie die Variable ändern, mit der Sie sie definiert haben. Ich bemerke auch, dass 'm' und' n' in 'need [n] [m]' transponiert sind. –
Bitte ändern Sie die Frage nicht, um die Probleme zu beheben. Tun Sie das auf Ihrem eigenen Schreibtisch, oder es macht den Dialog irrelevant. –