簡體   English   中英

fscanf導致分段錯誤

[英]fscanf results in a segmentation fault

void RdImage(FILE *fpi, char Image1[MAXROW][MAXCOL], int Nrows, int Ncols) {
    int i = 0, j = 0, temp;

    while (!feof(fpi)) {
        if (i % Nrows == 0) {
            i = 0; 
            j++;
        }

        **fscanf(fpi, "%d", temp);**     

        if (temp == 1) {
            Image1[i][j] == AP;
        } else {
            Image1[i][j] == PL;
        }
        i++;
    }
}

我用星號括起來的那行給我一個分割錯誤。 該文件絕對不是空的。 我在程序的其他地方使用過兩次相同的行,並且在該行中沒有這種行為。

temp是一個整數; 您必須通過其地址:

fscanf(fpi, "%d", &temp);

在編譯器中打開警告以捕獲此類錯誤。

根據C99 Std

7.19.6.2 fscanf函數

%d
匹配一個可選的帶符號十進制整數,其格式與strtol函數的主題序列的預期格式相同,且基本參數的值為10。

The corresponding argument shall be a pointer to signed integer.

所以

fscanf(fpi, "%d", &temp); //Here Address of temp is passed.

是正確的。

請在fscanf中使用&temp而不是temp

fscanf(fpi,“%d”,&temp);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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