C Unions output unclear

家住魔仙堡 提交于 2020-01-21 10:20:13

问题


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. that's all I got from reading and I dont know why the output is

1820, 28, 28

回答1:


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.

In your case, int (4 bytes), char, char (1 byte). Total memory allocation for whole union object is 4 bytes.

4bytes = _ _ , _ _, _ _ , _ _ (memory location representation)

assignment to year 1984 = 0x000007c0 (memory after first assignment)

assignment to month will use same location = 0x00000707 (only 1 byte is changed)

assignment to day 28 (0x1c) = 0x0000071c (final memory state)

Now get day (1byte) = 0x1c (28)

get month (1byte) = 0x1c (28)

get year (4byte) =0x0000071c (1820)

This is the whole story.




回答2:


It's 4 bytes but the month lays on top of the year as does the day. 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.



来源:https://stackoverflow.com/questions/37645472/c-unions-output-unclear

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!