Union and memory management

122 views Asked by At

I was at an interview and the following code was given to me:-

union mix
{
    int i;
    char c[2];
};

int main()
{
    union mix key;
    key.i=512;
    printf("\n %d,%d,%d",key.i,key.c[0],key.c[1]);
    return 0;   
}

and when I came home and ran it on the system I got the output:- 512,0,2.

Can anyone explain it to me how it works or why is c[1]=2?

Edit :- all I know is that it is related to bit storage in the memory.

1

There are 1 answers

3
Moshe Gottlieb On BEST ANSWER

It's a union, meaning i and c occupy the same memory.
512 is 0x200, meaning first byte is zero, second is 2 (each byte takes two hex digits).
This of course depends on the endianness of your CPU.