STHB STHB - 3 months ago 21
C Question

Writing two matrices to a .dat file using C

I'm writing a code that will some matrices and put them in a .dat file using C.

I'm writing in NetBeans as an IDE. Netbeans says the code is good for build but when it runs it fails and doesn't even tell me why.

Could there possibly be something wrong with the IDE I am using?

Here is the section of code (yes I have stdio.h and stdlib.h included in the source file).

//this is supposed to make a pair of example matrices.
double A[10][10];
double B[10][10];

int i , j;

for (i=0; i < 10 ; i++)
for(i=0; i < 10 ; i++)
A[i][j]= 1.0 ;
B[i][j]= 1.0 ;

//this is supposed to make the .dat file
FILE *fp2;

fp2 = fopen("MatricesFile.dat","w");

if(fp2 == NULL)
printf("Error in opening file");
return 1;

for(int i = 0 ; i < 10 ; i++)
for(int j = 0 ; j < 10 ; j++)
fwrite(&A[i][j], sizeof(A[i][j]), 1, fp2);
fwrite(&B[i][j], sizeof(B[i][j]), 1, fp2);


Thanks for any help.


Two obvious problems in the code.

When nesting loops, control inner loops and outer loops using different variables. At least one of your loops uses i to control both inner and outer loop.

When using fwrite() and fread(), open the file in binary mode (e.g. to open for writing, use mode "wb"). Otherwise data written out is not necessarily recovered correctly when reading.

And get out of the habit of blaming your IDE or compiler whenever you encounter a problem. IDEs and compilers have bugs, sure, but the vast majority of problems you encounter will be due to flaws in your coding. As is the case here.