为什么union和inner struct添加填充?

Nic*_*nks 3 c padding unions

在amd64上,以下结构的大小为16个字节:

typedef struct _my_struct {
    void *a;
    UINT32 b;
    UINT16 c;
    UINT8 d;
    UINT8 e;
} my_struct;
Run Code Online (Sandbox Code Playgroud)

但是当我把前三个变量放在一个联合中时,大小变为24.为什么?

typedef struct _my_struct {
    union {
        struct {
            void *a;
            UINT32 b;
            UINT16 c;
        } my_inner;
        struct {
            void **f;
        } my_inner2;
    }
    UINT8 d;
    UINT8 e;
} my_struct;
Run Code Online (Sandbox Code Playgroud)

Sam*_*ter 7

您正在创建一个新的结构类型(my_inner).编译器为此结构添加填充,使其大小为16字节(对于amd64).然后它将padding添加到外部struct type(my_struct),这使得它的大小增加到24个字节.

  • @NickBanks因为指定结构将在它出现的任何地方布局相同.否则你会在复制周围的东西时遇到麻烦.这种疯狂有方法! (2认同)