简体   繁体   English

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

so since it's an union it will give me 4 bytes, because int is the highest type given in this union. 因此,由于它是一个联合,它将给我4个字节,因为int是此联合中给出的最高类型。 that's all I got from reading and I dont know why the output is 这就是我从阅读中得到的全部信息,我不知道为什么输出是

1820, 28, 28

Unions in C use same memory allocation for variables defined in union. C中的联合对联合中定义的变量使用相同的内存分配。 So, the total allocation is equal to size of the variable that need largest memory area. 因此,总分配等于需要最大存储区的变量的大小。

In your case, int (4 bytes), char, char (1 byte). 您的情况是int(4个字节),char,char(1个字节)。 Total memory allocation for whole union object is 4 bytes. 整个联合对象的总内存分配为4个字节。

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

assignment to year 1984 = 0x000007c0 (memory after first assignment) 分配给1984年= 0x000007c0 (第一次分配后的内存)

assignment to month will use same location = 0x00000707 (only 1 byte is changed) 分配给月份将使用相同的位置= 0x00000707 (仅更改1个字节)

assignment to day 28 (0x1c) = 0x0000071c (final memory state) 分配给第28天(0x1c)= 0x0000071c (最终内存状态)

Now get day (1byte) = 0x1c (28) 现在获取日(1byte)= 0x1c (28)

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

get year (4byte) = 0x0000071 c (1820) 获取年份(4byte)= 0x0000071 c(1820)

This is the whole story. 这就是整个故事。

It's 4 bytes but the month lays on top of the year as does the day. 它是4个字节,但是月份和日期一样位于年份的顶部。 The last thing you stored, the day, clobbered whatever was there for month and year. 您存储的最后一件事,一天,一天到一年都被破坏了。 You can't access all three members in their original state. 您不能以其原始状态访问所有三个成员。 You can only pick one, the last one you stored. 您只能选择一个,即您存储的最后一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM