[英]How to get the size of a structure with dynamically allocated content ? (C)
我目前面临一个问题,我想将结构保存在二进制文件中,但结构的大小似乎每次都是错误的。
这是我的结构代码:
typedef struct {
int lines;
int columns;
int ** matrix;
char * name;
} labyrinthe;
这就是我将它保存在文件中的方式:
void writeInFile (labyrinthe * l, FILE * f) {
fwrite(l, sizeof(l), 1, f); //already tried with &l instead of l
}
但是,即使矩阵大小是 111*111 的网格,该文件也始终恰好包含 22 个字节。 任何帮助将不胜感激。
感谢阅读。
好吧,实际上该结构存储的正是您告诉它存储的内容,即:
2 个整数,一个 int 指针(指向另一个指针)和一个指向 char 的指针我认为在您的系统上 sizeof(int)=4 和 sizeof(type*)=8 这就是为什么您的文件中有 24 个字节.
为了更清楚,看看这个:
#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;
}
文件的十六进制转储看起来像这样(字节顺序因为字节序而切换)
|lines4b | columns 4b | matrix 8 bytes | name 8 bytes |
0001 0000 0002 0000 abcd abcd abcd abcd b00b 5000 0000 0000
矩阵和名称中的实际内容存储在内存中的另一个位置,结构中的那些指针仅指向该位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.