联盟规模大于预期.如何在这里进行类型对齐?

Wil*_*ill 4 c pointers sizeof alignment unions

#include <stdio.h>

union u1 {
    struct {
        int *i;
    } s1;
    struct {
        int i, j;
    } s2;
};

union u2 {
    struct {
        int *i, j;
    } s1;
    struct {
        int i, j;
    } s2;
};

int main(void) {
    printf("        size of int: %zu\n", sizeof(int));
    printf("size of int pointer: %zu\n", sizeof(int *));
    printf("   size of union u1: %zu\n", sizeof(union u1));
    printf("   size of union u2: %zu\n", sizeof(union u2));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果是:

$ gcc -O -Wall -Wextra -pedantic -std=c99 -o test test.c
$ ./test
        size of int: 4
size of int pointer: 8
   size of union u1: 8
   size of union u2: 16
Run Code Online (Sandbox Code Playgroud)

为什么在union u2的嵌套struct s1中添加一个4字节的整数会使整个联合的大小增加8个字节?

Nor*_*sey 8

u2.s2由于对齐约束,结构是16个字节.编译器保证如果你创建这样的结构数组,每个指针将在8字节边界上对齐.该字段*i占用8个字节,然后j占用4个字节,编译器插入4个字节的填充.因为结构是16个字节,所以包含它的联合也是16个字节.