I came across this objective question on the C programming language. The output for the following code is supposed to be 0 2
, but I don't understand why.
Please explain the initialization process. Here's the code:
#include <stdio.h>
int main()
{
union a
{
int x;
char y[2];
};
union a z = {512};
printf("\n%d %d", z.y[0], z.y[1]);
return 0;
}
I am going to assume that you use a little endian system where sizeof int
is 4 bytes (32 bits)
and sizeof a char
is 1 byte (8 bits)
, and one in which integers are represented in two's complement form. A union
only has the size of its largest member, and all the members point to this exact piece of memory.
Now, you are writing to this memory an integer value of 512
.
512 in binary is 1000000000
.
or in 32 bit two's complement form:
00000000 00000000 00000010 00000000
.
Now convert this to its little endian representation and you'll get:
00000000 00000010 00000000 00000000
|______| |______|
| |
y[0] y[1]
Now see the above what happens when you access it using indices of a char
array.
Thus, y[0]
is 00000000
which is 0
,
and y[1]
is 00000010
which is 2
.