Ersin Yılmaz Aslan
Ersin Yılmaz Aslan

Reputation: 43

How to write 2d dynamic array to a file in C

 int row,col,i,j;
 int **matrix;

 printf("Col:");
 scanf("%d",&col);
 printf("Row:");
 scanf("%d",&row);

 matrix= (int**) malloc(row* sizeof(int));
    if(NULL == matrix)
      {
      free(matrix);
      printf("Error.\n");
      exit(-1);
      }
for (i=0;i<row;i++)
{
  matrix[i] = (int*) malloc(col* sizeof(int));
    if(NULL == matrix[i])
      {
       free(matrix[i]);
       printf("Error.\n");
       exit(-1);
      }
}

for (i=0;i<col;i++)
   {
       for (j=0;j<row;j++)
     {
       matrix[i][j]=1+rand()%1000000;
     }
   }
FILE *tfile;


tfile=fopen("matrix.txt","w");
fwrite(matrix,sizeof(matrix),matrix,tfile);
fclose(tfile);

So my problem is whenever I try to execute this code output is being cryptic like this: ˜1œ °1œ È1œ à1œ a™w ¬Æ <
How do you write 2d array into a file if it is dynamic array? And what am I doing it wrong?

Upvotes: 0

Views: 249

Answers (2)

This is wrong:

matrix= (int**) malloc(row* sizeof(int));

It should be sizeof(int*) instead of sizeof(int).

This is wrong too:

for (i=0;i<col;i++)
   {
       for (j=0;j<row;j++)
     {
       matrix[i][j]=1+rand()%1000000;

When you allocated the arrays, you had row first and col second, but now you have col first and row second. It should be matrix[j][i] instead of matrix[i][j].

And this is really, really wrong:

fwrite(matrix,sizeof(matrix),matrix,tfile);

Why would you think a pointer is a suitable value for nmemb? And pointers aren't arrays. You have a pointer, not an array, so you can't use a single call to fwrite to write out everything. You'll need to do this row-by-row from inside of a loop.

And even with your program working right, you'll still get "cryptic" output, since you'll be writing a bunch of random numbers in binary form. If you want them to be ASCII text, then you'll have to use something like fprintf instead of fwrite.

Upvotes: 2

MrBens
MrBens

Reputation: 1260

You need to fix this line:

matrix= (int**) malloc(row* sizeof(int));

into this

matrix= (int**) malloc(row* sizeof(int*));

Edit: as Joseph pointed, that is not the only problem in the code.

Upvotes: 0

Related Questions