我正在尝试验证结构的大小。由于某些原因,它给了我 18 的大小,而不是预期的 14 字节(联合的最大值应该为 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