C Unions output unclear

2019-02-21 02:29发布

问题:

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.



标签: c unions