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
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With