Tyler Sebastian
Tyler Sebastian

Reputation: 9448

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++;
    }
}

The line I've inclosed in asterisks is giving me a segmentation fault. The file is definitely NOT empty. I've used the same line twice elsewhere in my program and it doesn't behave this way there.

Upvotes: 1

Views: 1698

Answers (3)

Jeyaram
Jeyaram

Reputation: 9474

As per C99 Std

7.19.6.2 The fscanf function

%d
Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument.

The corresponding argument shall be a pointer to signed integer.

so

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

is the correct one.

Upvotes: 1

Riskhan
Riskhan

Reputation: 4472

please use &temp instead of temp in fscanf

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

Upvotes: 0

nneonneo
nneonneo

Reputation: 179392

temp is an integer; you have to pass its address:

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

Turn on warnings in your compiler to catch bugs like this.

Upvotes: 7

Related Questions