I got the output 0 2 for this program…..
but don’t know why?
Please explain i think only int i is initialized with 512.
But how ch[1] got the value 2.
#include <stdio.h>
int main()
{
union a /* declared */
{
int i; char ch[2];
};
union a z = { 512 };
printf("%d%d", z.ch[0], z.ch[1]);
return 0;
}
Union declaration means that all its members are allocated the same memory. So your
int iandchar ch[2]are referencing the same memory space — in other words, they are aliased. Whenever you change one, you will change the other as well.Now, assuming your
ints are 32-bit wide and you’re on a little-endian system like x86,i = 512(512 == 0x00000200) actually looks like this in memory:with the first two values corresponding directly to the 2-character array:
So you get
ch[0] == 0x0andch[1] == 0x02.Try setting your
i = 0x1234and see what effect it will have on your character array.Based on your question, it’s possible that you may want to use a
structinstead ofunion— then its members would be allocated in memory sequentially (one after the other).