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
.
The memory allocated for the union is the size of the largest type in the union, which is int
in this case. Let's say the size of int
on your system is 2 bytes then
512
will be 0x200
.
Represenataion looks like:
0000 0010 0000 0000 | | | ------------------- Byte 1 Byte 0
So the first byte is 0
and the second one is 2
.(On Little endian systems)
char
is one byte on all systems.
So the access z.y[0]
and z.y[1]
is per byte access.
z.y[0] = 0000 0000 = 0 z.y[1] = 0000 0010 = 2
I am just giving you how memory is allocated and the value is stored.You need to consider the below points since the output depends on them.
Points to be noted:
sizeof(int)
matters, which will vary across the systems.PS: The memory occupied by both the members is the same in union.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With