Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 419
LazerSharks Avatar asked Dec 16 '22 10:12

LazerSharks


2 Answers

As i know you should use:

for(int n = 0; n < tI; n++)
{
  fwrite(heat[n], sizeof(float),sections, ofp);
}
like image 124
www.diwatu.com Avatar answered Dec 29 '22 01:12

www.diwatu.com


You can't write it out in one go, because each item in the heat array is allocated a separate segment of memory. You need to loop through the heat array and save one part at a time.

You'd need to do something more like this:

for (n = 0; n < tI; n++)
  fwrite(heat[n], sizeof(float), sections, ofp);
like image 36
James Holderness Avatar answered Dec 28 '22 23:12

James Holderness