Search code examples
cmultidimensional-arrayfwritedynamic-arrays

how do i write and read a three dimensional dynamic char array to a file?


i have this array

char ***three_dim=0;

three_dim is allocated and populated with data. After this I have to write its content to a file and read back. I have tried the following to write it but it fails.

FILE *temp;
temp=fopen("temp","w");
fwrite(three_dim,outer_dim*ROWS*COLUMNS,1,temp);
fclose(temp);

EDIT:

Here is how it is allocated:

three_dim=new char**[outer_dim];
         for(int i=0;i<outer_dim;++i)
            {
                three_dim[i]=new char*[ROWS];
                for(int k=0;k<ROWS;++k)
                    three_dim[i][k]=new char[COLUMNS];
            }

Solution

  • You cannot write it into file by a single fwrite(), because your array is not allocated as a compact area of outer_dim * ROWS * COLUMNS bytes.

    As you allocated it in a for-cycle, you must also output it in a for-cycle.

    for (i = 0; i < outer_dim; i++)
        for (j = 0; j < ROWS; j++)
            fwrite(three_dim[i][j], COLUMNS, 1, temp);