union a
{
int x;
char a[2];
}
If we assign 512 value to x and try to print a[0] and a[1] then what will be the output please explain how?
union a
{
int x;
char a[2];
}
If we assign 512 value to x and try to print a[0] and a[1] then what will be the output please explain how?
I the depends on the endianess of the platform. On little-endian platforms (Intel) a[0] will have the least significant byte of the integer (4 bytes), so a[0] will hold 0x00 and a[1] 0x02
Unions in C share same memory space, that is, both x and a[2] start at the same memory location. When you assign the value to one of them, the other gets overwritten.
In your case, when you assign 512 to x, you'll write it's bytes to char as well, like Fernando Miguélez just explained...
According to the standard, the result of writing to one member of a union, then reading from another isn't defined. Just about anything could happen.
Realistically, if you run the code on a little-endian machine, a[0] will probably be 0, and a[1] will probably be 2. On a 16-bit big-endian machine, a[0] would be 2 and a[1] would be 0. On a 32-bit big-endian machine, (the nonexistent, as you've defined things) a[2] would be 2, and a[0], a[1], &a[3] would be 0.
It depends on the endian-ness of the computer you run it on:
union in effect uses the same memory for your int and your chars, so,
int 512 (ie 0x200) char[4] 0x00 0x00 0x02 0x00 little endian, so a[0]=0, a[1]=0 char[4] 0x00 0x02 0x00 0x00 big endian , so a[0]=0, a[1]=2
(actually, I might have little & big endian the wrong way around)