Reputation: 29
The ouput of the following code is coming out to be 512 0 2 however it should have been 512 0 0. Can somebody please help !
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a z = { 512 };
printf("%d %d %d\n",z.i, z.ch[0], z.ch[1]);
return 0;
}
Upvotes: 1
Views: 260
Reputation: 4288
You have build a union of two bytes. Know you assign 512d (0x0200) to the union.
First Byte = 0x00
Second Byte = 0x02
The integer (int16_t
) i
and your array ch[2]
use the same memory!
Upvotes: 5
Reputation: 749
I think you have some confusion with a struct and a union.
A union uses the same memory for all of its members and a struct has a separate memory for each member.
See the following extension of your code (at IDEone ):
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a aa = { 512 };
printf("%d %d %d\n",aa.i, aa.ch[0], aa.ch[1]);
struct b
{
int i;
char ch[2];
};
struct b bb = { 512 };
printf("%d %d %d\n",bb.i, bb.ch[0], bb.ch[1]);
return 0;
}
Output:
Union: 512 0 2
Struct: 512 0 0
Upvotes: 2
Reputation: 795
Let's assume for simplicity that int is 2 bytes.In this case the memory for your struct will be 2 bytes.Let's also assume that the union is located on address 0x0000.By the results you are getting i can tell you're using a little endian machine - address 0x0000 -> value 0x0000, address 0x0002 -> value 0x0002.
z.i
prints 512 correctly.
z.ch[0]
getting the value from address 0x0000 which is 0
z.ch[1]
getting the value from address 0x0002 which is 2
Big Endian Byte Order: The most significant byte (the "big end") of the data is placed at the byte with the lowest address. The rest of the data is placed in order in the next three bytes in memory.
Little Endian Byte Order: The least significant byte (the "little end") of the data is placed at the byte with the lowest address. The rest of the data is placed in order in the next three bytes in memory.
Upvotes: 4