0

Basically, the input file should look like this:

4
1 2 3 4
2 1 4 3
4 3 2 1
3 4 1 2

Where the first line is the size of the square matrix. However, I can't properly load the input directly into n and then into the matrix. I avoided such problem by creating a "loader" array.

int n, loader[100], p=0;
while(feof(data) == 0) {
    if(p == 0) {
        fscanf(data, "%d", &n); //taking n
        p++;
    } else {
        fscanf(data, "%d", &loader[p]); //taking matrix values for p>0
        p++;
    }
}

//loading the matrix
int mat[n][n], o = 1; //o is set to 1, as the loader
                      //has been loaded from position 1.
for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++){
        printf("%d\n", loader[o]);
        mat[i][j] = loader[o];
        o++;
    }
}

However, I think it is just unnecessary and there might be a faster way to directly take the matrix size and its values. When I programmed in such way, I received a welcoming Segmentation Fault error.

Habras
  • 21
  • 8
  • Yes you are right. You don't need `loader`. Can read straight into `&mat[i][j]`. Just read `n` first then have a seperate loop to read the `mat` values. – kaylum Jan 14 '20 at 11:01
  • 5
    [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – kaylum Jan 14 '20 at 11:02
  • I'll retry and tell you if I still get segmentation error – Habras Jan 14 '20 at 11:07
  • I think one error is also, that `int mat[n][n]` doesn't work, as you would have to allocate an 2d-array dynamically. – skratpa Jan 14 '20 at 11:10
  • 1
    @unrealguthrie [VLS](http://port70.net/~nsz/c/c11/n1570.html#6.7.6.2p10)'s are allowed in c – TruthSeeker Jan 14 '20 at 11:12
  • @TruthSeeker yep, you're right. sorry. – skratpa Jan 14 '20 at 11:15
  • I could also define mat[100][100] and work on the first n lines and rows, but that doesn't quite satisfy me. I have to get a way to dynamically allocate memory to that matrix. – Habras Jan 14 '20 at 11:32

1 Answers1

2

This code seems to work:

int loadMatrix(char *pth)
{
    int i, j, n, **mat, p = 0, num;
    FILE *fd;

    fd = fopen(pth, "r");
    if(fd == NULL) return(-1);

    /* Read matrix size */
    if(fscanf(fd, "%d", &n) == EOF) return(-1);
    printf("Size: %d\n", n);

    mat = malloc(n * sizeof(int *));
    for(i = 0; i < n; i++) mat[i] = malloc(sizeof(int) * n);

    while(fscanf(fd, "%d", &num) != EOF && p < (n * n)) {
        mat[p / n][p % n] = num;
        p++;
    }

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

    for(i = 0; i < n; i++) free(mat[i]);
    free(mat);

    fclose(fd);
    return(0);
}
skratpa
  • 130
  • 12
  • @Habras I improved the code a bit more because it still had it flaws. But now it should be good enough. – skratpa Jan 14 '20 at 12:02