hgajshb
hgajshb

Reputation: 225

Dynamically allocated array cannot be used with fscanf?

I am trying to use fscanf to store a file of ints separated by space into an array. This is the code:

#include <stdio.h>
int main(void)
{
    FILE* fp = fopen("a.txt", "r");
    int m = 0, n = 0;
    int i, j;
    char temp[256];
    while (fgets(temp, 256, fp) != NULL)
        m++; //gets m
    for (i = 0; i < strlen(temp); i++)
        if (temp[i] == ' ')
            n++;
    n++; //gets n
    int num[m][n];
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            fscanf(fp, "%d", &num[i][j]);
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
            printf("%d", num[i][j]);
        puts(""); //prints the VLA
    }
    return 0;
}

And the file (a.txt) looks like this:

0 0 0  
0 0 0

But what I get is like this:

16537088  11532152  13701243  
11531888         3  13701455

What could be the problem? Anything wrong with the code?

Upvotes: 1

Views: 56

Answers (1)

CH.
CH.

Reputation: 606

There are numerous issues here, not to do with variable length (actually dynamically allocated in your case) arrays:

  1. You use fgets to read through the file once, meaning the file pointer is now pointing at the end of the file. When you use fscanf, it tries to read past the end of file instead of reading from the start as desired.

  2. You forgot to #include <string.h> for strlen.

  3. When printing the values, you need to add a space after %d in order to print the values with spaces apart.

Lastly, this method of dynamically allocating arrays is not recommended. It is better to use malloc and free as seen here, although this will work assuming you're using C99 or later that allows this syntax.

My fixed code is:

#include <stdio.h>
#include <string.h>

int main(void)
{
    FILE* fp = fopen("a.txt", "r");
    int m = 0, n = 0;
    int i, j;
    char temp[256];
    while (fgets(temp, 256, fp) != NULL)
        m++; //gets m
    for (i = 0; i < strlen(temp); i++)
        if (temp[i] == ' ')
            n++;
    n++; //gets n
    int num[m][n];

    fclose(fp);
    fp = fopen("a.txt", "r");

    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            fscanf(fp, "%d", &num[i][j]);
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
            printf("%d ", num[i][j]);
        puts(""); //prints the VLA
    }
    return 0;
}

Note the closing and reopening of the file as well as the other fixes I mentioned.

Upvotes: 3

Related Questions