I'm currently facing an issue where I want to save a structure in a binary file, but the size of the structure seems to be wrong everytime.
Here is the code of my structure :
typedef struct {
int lines;
int columns;
int ** matrix;
char * name;
} labyrinthe;
And this is how I'm saving it in a file :
void writeInFile (labyrinthe * l, FILE * f) {
fwrite(l, sizeof(l), 1, f); //already tried with &l instead of l
}
However, the file always contains exactly 22 bytes, even if the matrix size is a 111*111 grid. Any help would be really appreciated.
Thanks for reading.
Well, actually the structure stores exactly what you tell it to store and that is:
2 ints, one int pointer(which points to another pointer) and a pointer to a char And I think on your system sizeof(int)=4 and sizeof(type*)=8 and that's why you would have 24 bytes in your file.
To make it more clear take a look at this:
#include<stdlib.h>
#include<stdio.h>
typedef struct {
int lines;
int columns;
int ** matrix;
char * name;
} labyrinthe;
int main(void)
{
FILE *f = fopen("file","w+b");
labyrinthe *l;
l=malloc(sizeof(labyrinthe));
l->lines=1;
l->columns=2;
l->matrix = 0xABCDABCDABCDABCD;
l->name = 0x5000B00B;
fwrite(l, sizeof(*l), 1, f);
return 0;
}
And the hexdump of the file looks like this (byte order switched because of endianess)
|lines4b | columns 4b | matrix 8 bytes | name 8 bytes |
0001 0000 0002 0000 abcd abcd abcd abcd b00b 5000 0000 0000
The actual content of what is in the matrix and name is stored in another place in memory, and those pointers in the structure just point to that place.