Reading matrix from text file in c

I am trying to read a text file and store data in a matrix. I print the results after reading each row and it seems to work, but if I print the matrix at the end, I don't have the same results. I can not find what I am 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 result of the program:

 1 2 3 4 5 6 7 8 9 Your matrix: 1 2 4 4 5 7 7 8 9 
+6
source share
1 answer

You declare double value[10000][2]; , but then refer to value[i][2] . An array declared using [2] contains 2 elements, indexed 0 and 1 . Accessing index "2" overwrites another memory.

Using

 double value[10000][3]; 
+6
source

Source: https://habr.com/ru/post/985205/


All Articles