Q:

Multidimensional array - fscanf

int main(){
int word, r=3, i, j;
FILE *fp1 = fopen("key.txt","r");

int **arr  = (int **)malloc(sizeof(int *) * r);

for(i = 0;i<r;i++)
    arr[i] = (int *)malloc(sizeof(int)*r);

int a = 0, b = 0;
while (!feof(fp1)) {
    fscanf(fp1,"%d",&word);
    if (b == r){
        a++;
        b=0;
        continue;
    }

    arr[a][b++] = word;

}

for (i = 0; i <  r; i++)
    for (j = 0; j < r; j++)
        printf("%d \n", arr[i][j]);

fclose(fp1); 
}

And this is my key.txt.

0 -1 0
-1 2 -1
0 -1 0

I want to store key.txt in a dynamic 2d array but it did not work. All the time a part of it is missing. Which part is wrong?

A:

You should use fscanf in while, not feof
You should delete continue.

The follow code could work:
#include <stdio.h>
#include <stdlib.h>

int main(){
    int word, r=3, i, j;
    FILE *fp1 = fopen("key.txt","r");

    int **arr  = (int **)malloc(sizeof(int *) * r);

    for(i = 0;i<r;i++)
        arr[i] = (int *)malloc(sizeof(int)*r);

    int a = 0, b = 0;
    while (fscanf(fp1,"%d",&word) == 1) {
        if (b == r) {
            a++;
            b=0;
        }
        arr[a][b++] = word;
    }

    for (i = 0; i < r; i++) {
        for (j = 0; j < r; j++)
            printf("%d ", arr[i][j]);
        printf("\n");
    }

    fclose(fp1);
    return 0;
}

