C联盟输出不清楚

koi*_*oin 0 c unions

理解工会及其运作方式我遇到了一些麻烦.

#include <stdio.h>

union date {
    int year;
    char month;
    char day;
};

int main() {
    union date birth;
    birth.year = 1984;
    birth.month = 7;
    birth.day = 28;
    printf("%d, %d, %d\n", birth.year, birth.month, birth.day);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

因为它是一个联合,它会给我4个字节,因为int是这个联合中给出的最高类型.这就是我从阅读中得到的所有内容,我不知道输出为什么

1820, 28, 28
Run Code Online (Sandbox Code Playgroud)

Ock*_*ius 5

C中的联合对联合中定义的变量使用相同的内存分配.因此,总分配等于需要最大内存区域的变量的大小.

在你的情况下,int(4字节),char,char(1字节).整个联合对象的总内存分配是4个字节.

4bytes = _ _,_ _,_ _,_ _(内存位置表示)

分配到1984年= 0x000007c0(首次分配后的内存)

对月份的分配将使用相同的位置= 0x00000707(仅更改1个字节)

分配到第28天(0x1c)= 0x0000071c(最终内存状态)

现在得到一天(1byte)= 0x1c(28)

得到月(1byte)= 0x1c(28)

得到年份(4byte)= 0x0000071 c(1820)

这是整个故事.