簡體   English   中英

“打包”后的結構仍然大於應有的大小

[英]structure after “packed” still bigger than it should be

問題解決了。 錯誤是沒有重新考慮給定的數據類型......以下結構的大小比它應該的要大:

typedef unsigned char    byte;
typedef unsigned short   word;
typedef unsigned long    dword;

struct Y
{
 short      h;
 byte       i;       
}
#if defined (__GNUC__)
    __attribute__((__packed__));
#endif

struct X
{
   short    a;
   byte     b;
   byte     c;
   word     d;
   dword    e;
   byte     f;
   byte     g;
   word     h;
   short    i;
   struct Y G[8];
}
#if defined (__GNUC__)
    __attribute__((__packed__));
#endif

printf("size of X should be 40 but is %i", sizeof(struct X));

Output:

size of X should be 40 but is 44

我需要這個大小為 40 字節(所有元素的總和)的結構,44 是我能達到的最低值。 編譯器是 GCC C, byteunsigned charwordunsigned shortdwordunsigned long sizeof(Y)為 3。這里有什么問題?

您定義的類型有缺陷。 理想情況下,我認為dword應該是word大小的兩倍,但您將兩者定義為:

typedef unsigned short   word;  
typedef unsigned long    dword; 

事實證明,在您的平台上sizeof(unsigned short)2 ,而sizeof(unsigned long)8而不是4

您應該真正避免此類定義並使用stdint.h中提供的標准類型:

byte  -> uint8_t
short -> uint16_t
word  -> uint16_t
dword -> uint32_t

最后,如果宏__GNUC__未定義,您的結構聲明無效,因為您會丟失最后的分號 ( ; )。 你可以把它改成這樣:

#if defined (__GNUC__)
__attribute__((__packed__))
#endif
struct Y
{
 uint16_t h;
 uint8_t  i;       
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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