Question

So I find the number of lines in an unknown matrix and then want to use this number to scan through the matrix the correct number of times and display the matrix at the end. I need to find the dimension as i want to go on to find the determinant but this is my code so far.

Anyway the problem is that the "dim" integer doesn't seem to transfer as it prints out a bunch of crazy numbers

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main(int argc, char* argv[])
{
    FILE       *input;
    int        i, j, temp, dim;  
    float      fullmatrix[dim][dim];
    const char inp_fn[]="matrix.dat";

/*Open File*/
input = fopen(inp_fn, "r");
dim = 0;

while (EOF != (temp = fgetc(input)))
{
    if (temp=='\n')
    {
        ++dim;
    }
}

if( (input != (FILE*) NULL) )
{
    for(i=0; i<=dim; i++)
    {
        for(j=0; j<=dim; j++)
        {
            fscanf(input, "%f", &fullmatrix[i][j]);
            printf("%f ", fullmatrix[i][j]);
        }
        printf("\n");
    }
    fclose(input);
}
else
{
    printf("Could not open file!\n");
}

return(0);
}

I'm pretty new to this so i'm probably being stupid.

Was it helpful?

Solution

I found this code to work...but read the comments \\ and note the comment on variable length arrays (VLA).

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main(int argc, char* argv[])
{
    FILE       *input;
    int        i, j, temp, dim;  

    const char inp_fn[]="matrix.dat";

/*Open File*/
input = fopen(inp_fn, "r");
dim = 0;

while (EOF != (temp = fgetc(input)))
{
    if (temp=='\n')
    {
        ++dim;
    }
}

float fullmatrix[dim][dim];  // define fullmatrix after dim is known

// we close and reopen the file. We could also move back to the beginning of the file.
fclose(input);

printf("%d\n", dim);

input = fopen(inp_fn, "r");

// Probably not the safest way...we just assume that the file has not change after we 
// determined dim
for (i=0; i<dim; i++) 
 {  
    for(j=0; j<dim; j++)
    {
       fscanf(input, "%f", &fullmatrix[i][j]);
        printf("%f ", fullmatrix[i][j]);
    }
    printf("\n");
}

fclose(input);


return(0);
}

Example output:

3
1.000000 2.000000 3.000000 
4.000000 5.000000 6.000000 
7.000000 8.000000 9.000000 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top