簡體   English   中英

C 分段錯誤 fscanf

[英]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時, nm初始化。 嘗試在int max[m][n];之前打印nm 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];

現在,當您創建數組時, nm將使用從文件中讀取的值進行初始化。


如果你想在讀取nm之前聲明你的數組,那么你應該使用指針,讀取nm然后動態分配數組

您聲明int max[m][n], allo[m][n], need[n][m]mn尚未設置,因此它們的大小未知。 設置大小后,它們不會自行調整大小。 所以寫這些會給你“未定義的行為”

由於 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 的值沒有定義。

您可以將maxalloneed定義為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM