Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a matrix from a text file in c

I´m trying to read a text file and store the data in a matrix. I print the results after read each line and seems it is working, but if I print the matrix at the end, I don't have the same results. I can't find what i'm doing wrong!

int main()
{
    int i,j;
    double value[10000][2];
    FILE *archivo;
    archivo = fopen("pruebas.txt","r");
    if (archivo == NULL)
        exit(1);
    i=0;
    while (feof(archivo) == 0)
    {
        fscanf( archivo, "%lf %lf %lf", &value[i][0],&value[i][1],&value[i][2]);
        printf("%10.0f %f %f\n", value[i][0], value[i][1], value[i][2]);
        i++;
    }

    printf("Your matrix:\n");
    for(j = 0; j < i; j++)
        printf("%10.0f %10.3f %10.3f\n", value[j][0], value[j][1], value[j][2]);

    fclose(archivo);
    return 0;
}

This is the output of the program:

1 2 3 
4 5 6  
7 8 9   
Your matrix:  
1 2 4  
4 5 7  
7 8 9  
like image 238
Rebeca Avatar asked Apr 15 '15 17:04

Rebeca


1 Answers

You declare double value[10000][2]; but then access value[i][2]. An array declared with [2] contains 2 elements, indexed 0 and 1. Accessing index '2' is overwriting other memory.

Use

double value[10000][3];
like image 107
Politank-Z Avatar answered Oct 10 '22 07:10

Politank-Z