c - 结构具有 union 时的意外大小

标签 c struct sizeof structure-packing

我正在尝试验证结构的大小。由于某些原因,它给了我 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/

相关文章:

c - C 中的位结构

c++ - sizeof 在编译不同的程序时为结构返回不同的值

c++ - sizeof运算符为VOID运算符返回1个字节

c - 未分配正在释放的指针,中止陷阱 : 6

c - 在包含未初始化指针的结构上使用 free

c++ - 使用由结构指向的指针中的变量,该结构(该结构的)指针被发送到需要使用它的函数

c - 为什么它的输出为 'bye' ?请讨论

c - 如何使用 if else 进行字符串比较?

c - 在 MacOS X 中安装 valgrind

c++ - 循环指针数组