C Programming - Structures, Unions, Enums - Discussion
Discussion Forum : Structures, Unions, Enums - Point Out Errors (Q.No. 8)
8.
Point out the error in the program?
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a z1 = {512};
union a z2 = {0, 2};
return 0;
}
Discussion:
21 comments Page 3 of 3.
Aishwarya said:
4 years ago
The difference between structure and union is the size of the structure is the sum of the size of its data members, whereas the size of the union is the size of the largest element.
All members of the union share the same memory space.
size of union = size of largest datatype element
So here the size of the union is 4 bytes and shared by integer and char array, so redeclaration should overwrite the values.
union a z2 = {0, 2}; // gives warning: excess elements in union initializer.
printf("%d\n",z1);// if we print z1 it prints 512.
z1.i =16961; / / redeclare z1 will overwrite its value because its a union.
z1.ch; / / array will store the same value but split it bitwise.
0100 0010 0100 0001 =16961 (16384 + 512 + 64 +1)
0100 0010 =66(64+2) 0100 0001=65(64+1)
B (ch[1]) A (ch[0])
printf("%d\n",z1); //now if we print z1 it prints 16961.
printf("%c %c\n",z1.ch[0],z1.ch[1]); // it prints A B.
This is how the union works as per my knowledge.
All members of the union share the same memory space.
size of union = size of largest datatype element
So here the size of the union is 4 bytes and shared by integer and char array, so redeclaration should overwrite the values.
union a z2 = {0, 2}; // gives warning: excess elements in union initializer.
printf("%d\n",z1);// if we print z1 it prints 512.
z1.i =16961; / / redeclare z1 will overwrite its value because its a union.
z1.ch; / / array will store the same value but split it bitwise.
0100 0010 0100 0001 =16961 (16384 + 512 + 64 +1)
0100 0010 =66(64+2) 0100 0001=65(64+1)
B (ch[1]) A (ch[0])
printf("%d\n",z1); //now if we print z1 it prints 16961.
printf("%c %c\n",z1.ch[0],z1.ch[1]); // it prints A B.
This is how the union works as per my knowledge.
(3)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers