Using fwrite and a double pointer to output a 2D array to a file

I dynamically allocated a 2D array that can be accessed with a double pointer:

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 its elements with values ​​(I'm sure that they are all filled correctly), I'm trying to output it to a file as follows:

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

I also just tried:

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

Am I trying to output this 2D array correctly?

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

I know that heat[tI-1][sections-1] also really within the 2D array. I just used it because I know the biggest element that I hold.

My conclusion is a lot of NULL, and sometimes strange system paths.

+4
source share
2 answers

As I know, you should use:

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

You cannot write it at a time, because each element of the heat array is allocated a separate memory segment. You need to go through the heat grid and save one part at a time.

You need to do something more:

 for (n = 0; n < tI; n++) fwrite(heat[n], sizeof(float), sections, ofp); 
+5
source

Source: https://habr.com/ru/post/1479994/


All Articles