C 联盟产出不明

标签 c unions

我在理解 union 及其运作方式时遇到了一些麻烦。

#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;
}

因为它是一个 union 体,所以它会给我 4 个字节,因为 int 是这个 union 体中给出的最高类型。这就是我从阅读中得到的全部,我不知道为什么输出是

1820, 28, 28

最佳答案

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

在您的例子中,int(4 个字节)、char、char(1 个字节)。整个 union 对象的总内存分配为 4 个字节。

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

分配给 1984 年 = 0x000007c0(第一次分配后的内存)

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

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

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

获取月份(1byte)= 0x1c (28)

获取年份(4byte)=0x0000071c (1820)

这就是整个故事。

关于C 联盟产出不明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645472/

相关文章:

c - 如何将此循环从 C 语言转换为 python 3?

c - Valgrind 错误 "Invalid write of size 4"C

c++ - 编译时错误: Union default constructor is deleted

C++ union 字段设置不正确

c - C atoi 函数中的潜在错误

字符串比较

c - 在 CentOS 上从 C 中的信号处理程序中调用时,localtime_r 卡在了锁上

关于C中union的代码片段问题

c++ - 将结构复制(使用赋值)到 union 内的结构导致段错误

c - 从文件读取时 union 导致段错误