So I've searched everywhere and for some reason my code isn't working. Here is what I want to do..

I am generating a .txt file with a matrix. The matrix is different each time, depending on input. So here is an example of one of the outputs that I can possibly have:

7 8 9

6 1 2

5 4 3

I malloced a multidimensional array that has the same size as the matrix in the file and initialized its contents to -1 as follows:

int **array; array = malloc(n * sizeof(int *)); if(array == NULL) { printf("Out of memory\n"); exit(1); } for(int i = 0; i < n; i++) { array[i] = malloc(n * sizeof(int)); if(array[i] == NULL) { printf("Out of memory\n"); exit(1); } } // Initialize matrix content to -1 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { array[i][j] = -1; } }

Now I want to read in the text file matrix and put each number in the corresponding position in the array. I've done all sorts of stuff, searched everywhere, used all the books I have and it is just not working.. Here are examples of what I tried to do:

When printing the array after doing the following, its contents are still -1:

int x; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { x = fscanf(pFile, "%d", &array[i][j]); } }

I've also tried to do a while loop and check for end-of-file, while (fscan...) != EOF and that did not work either.

Most posts online show methods on reading a matrix when you know the size of the matrix. However, my size of matrix is determined upon runtime. And all the methods I saw online are just not working..

I appreciate any help.

Thanks,