Kavya TKnowledge Contributor
What is the output of the program? #include<stdio.h> int main() { union a { int i; char ch[2]; }; union a u; u.ch[0] = 3; u.ch[1] = 2; printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i); return 0; }
What is the output of the program? #include<stdio.h> int main() { union a { int i; char ch[2]; }; union a u; u.ch[0] = 3; u.ch[1] = 2; printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i); return 0; }
Your defined union have two members…
1) int =====================> size =4 B
2) character array of length 2 ===> size =2 B
Therefore size of Union is 4B
You updated the Char member of Union at last ===> Character array is having the original value.
what about ” int ” ? (assume your system is following little endian)
it access the total 4B ===> ch[1] ch[0] ====> 00000010 00000011 ===> 512+3 = 515
if you have the doubt that why not accessing in the form of ch[0] ch[1] ====> 00000011 00000010 ===> 512+256+2 = 770