[英]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, byte
是unsigned char
, word
是unsigned short
和dword
是unsigned 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.