In union all elements refer to the same slot of memory. Thus if we consider int as 2 bytes ,then it contains the value in binary as 00000001 00000000(256). Since the size of char is 1 byte, so the first half(1 byte) should be allocated with 00000001 and the second half should be allocated with 00000000. But why does the following code print 256 0 1
rather than 256 1 0
?
#include<stdio.h>
int main()
{
union a{
int i;
char ch[10];
};
union a u;
u.i=256;
printf("%d,%d,%d",u.i,u.ch[0],u.ch[1]);
return 0;
}
You have a little-endian* machine.
The bytes of i are laid out with the low byte first.
If you had a big-endian machine the expected output would not have been "256 1 0" unless sizeof(int)
were 2. I don't think you have a 16 bit processor. On the more likely sizeof(int)
of 4, you would have the output of "256 0 0". Try this program:
#include<stdio.h>
int main()
{
union a{
int i;
char ch[sizeof(int)];
};
union a u;
u.i=256;
printf("%d", u.i);
for (int b = 0; b < sizeof(int); ++b)
printf(",%d", (int)(unsigned char)(u.ch[b]));
printf("\n");
return 0;
}
This will show you all the bytes of u.i
in order as your processor lays them out.
*Assuming you're not on a PDP. You don't want to know about PDP.