6

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  
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Rebeca
  • 63
  • 1
  • 1
  • 3
  • 2
    Please search on SO for the answer before asking. This question or something very similar has been asked, and answered, many times before. Your trouble is `double value[10000][2];` and `fscanf( archivo, "%lf %lf %lf", &value[i][0],&value[i][1],&value[i][2]);` -- you accessing the array out of bounds and overwriting stuff. – Jonathan Leffler Apr 15 '15 at 17:44
  • 2
    `while (feof(archivo) == 0)` - please refer to SO question http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong/5432004 You should also check the return value from `fscanf()`, in this case `if(3 != fscanf(...))` – Weather Vane Apr 15 '15 at 17:49
  • 1
    Instead of `while (!feof(archivo))` which will be `true` once after the last line is read, you can do `while (fscanf(...) == 3)` which not only ensures that the loop will perform the correct number of iterations, but also that the line contains well formated data. In fact `printf()` right after `fscanf()` potentially invokes undefined behavior. – Iharob Al Asimi Apr 15 '15 at 17:54
  • `feof()` only informs true if a read operation *previously* attempted to read past the end of the file. So it doesn't tell you there is no more to read - only if you already made a bad read - which as @iharob says, you can test just with the return value from `fscanf()`, and that way, you'll also trap a poorly formatted file. – Weather Vane Apr 15 '15 at 18:01
  • ... and of course, if you wan to read a matrix of three columns, dimension it adequately, as `double matrix[1000][3]; /* and not 2 */`. – Luis Colorado Apr 16 '15 at 08:46

1 Answers1

6

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];
R Sahu
  • 204,454
  • 14
  • 159
  • 270
Politank-Z
  • 3,653
  • 3
  • 24
  • 28