C 工会输出不清楚 [英] C Unions output unclear
问题描述
我在理解工会及其运作方式时遇到了一些麻烦.
I got some troubles understanding unions and how they work.
#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;
}
所以因为它是一个联合,它会给我 4 个字节,因为 int 是这个联合中给出的最高类型.这就是我从阅读中得到的,我不知道为什么输出是
so since it's an union it will give me 4 bytes, because int is the highest type given in this union. that's all I got from reading and I dont know why the output is
1820, 28, 28
推荐答案
C 中的联合对联合中定义的变量使用相同的内存分配.因此,总分配量等于需要最大内存区域的变量的大小.
Unions in C use same memory allocation for variables defined in union. So, the total allocation is equal to size of the variable that need largest memory area.
在您的情况下,int(4 个字节)、char、char(1 个字节).整个联合对象的总内存分配为 4 个字节.
In your case, int (4 bytes), char, char (1 byte). Total memory allocation for whole union object is 4 bytes.
4bytes = _ _ , _ _, _ _ , _ _(内存位置表示)
4bytes = _ _ , _ _, _ _ , _ _ (memory location representation)
分配到 1984 年 = 0x000007c0(第一次分配后的记忆)
assignment to year 1984 = 0x000007c0 (memory after first assignment)
分配给月份将使用相同的位置 = 0x00000707(仅更改 1 个字节)
assignment to month will use same location = 0x00000707 (only 1 byte is changed)
分配到第 28 天 (0x1c) = 0x0000071c(最终记忆状态)
assignment to day 28 (0x1c) = 0x0000071c (final memory state)
现在得到一天 (1byte) = 0x1c (28)
Now get day (1byte) = 0x1c (28)
获取月份 (1byte) = 0x1c (28)
get month (1byte) = 0x1c (28)
获取年份(4 字节)=0x0000071c (1820)
get year (4byte) =0x0000071c (1820)
这就是整个故事.
这篇关于C 工会输出不清楚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!