using fwrite and double pointer to output 2D array to file

LazerSharks picture LazerSharks · May 9, 2013 · Viewed 8.5k times · Source

I've dynamically allocated a 2D array, accessed w/ a double pointer, like so:

  float **heat;
  heat = (float **)malloc(sizeof(float *)*tI); // tI == 50
  int n;
  for(n = 0; n < tI; n++){ // tI == 50
            heat[n] = (float *)malloc(sizeof(float)*sections); // sections == 30
    }

After filling all of its elements with values (I'm sure they are all filled correctly), I'm trying to output it to a file like so:

fwrite(heat, sizeof(heat[tI-1][sections-1]), ((50*30)-1), ofp);

I've also just tried:

fwrite(heat, sizeof(float), ((50*30)-1), ofp);

Am I trying to output this 2D array right?

I know that my file I/O is working (the file pointer ofp is not null, and writing to the file in decimal works), but very strange characters and messages are being outputted to my output file when I try to use fwrite to write in binary.

I know that heat[tI-1][sections-1] is also indeed within the bounds of the 2D array. I was just using it because I know that's the largest element I'm holding.

My output is a lot of NULLs and sometimes strange system paths.

Answer

Gisway picture Gisway · May 9, 2013

As i know you should use:

for(int n = 0; n < tI; n++)
{
  fwrite(heat[n], sizeof(float),sections, ofp);
}