簡體   English   中英

如何獲取具有動態分配內容的結構的大小? (三)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM