我正在尝试验证结构的大小。由于某些原因,它给了我 18 个字节而不是预期的 14 个字节( union 应该有最大 8 + 2 + 2 = 12 个字节)。有人可以帮助我吗?
typedef struct __attribute__((__packed__)) def
{
union {
double x; /* 8 bytes */
char *y; /* 8 bytes as for 64-bit system */
struct {
struct def *array; /* 8 bytes */
unsigned short a; /* 2 bytes */
unsigned short b; /* 2 bytes */
} z;
} w;
unsigned short v; /* 2 bytes */
} DEF, *DEFP;
int main(int argc, char **argv) {
printf("size of DEF = %lu\n", sizeof(DEF));
printf("size of unsigned short = %lu\n", sizeof(unsigned short));
printf("size of struct def * = %lu\n", sizeof(struct def *));
printf("size of char * = %lu\n", sizeof(char *));
printf("size of double = %lu\n", sizeof(double));
}
这是我运行时显示的内容:
$ gcc test.c && ./a.out
size of DEF = 18
size of unsigned short = 2
size of struct def * = 8
size of char * = 8
size of double = 8
最佳答案
__attribute__((__packed__))
仅指 struct def
。它不会将匿名 struct
打包到 struct def
中的匿名 union
中。
很可能是那两个成员
unsigned short a; /* 2 bytes */
unsigned short b; /* 2 bytes */
“使用”4 个但 2 个字节。
与您的问题无关:C 要求使用 z
长度修饰符 打印 size_t
:
printf("size of DEF = %zu\n", sizeof (DEF));
关于c - 结构具有 union 时的意外大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48781938/