how a structure is different from union?
structure
Collapse
X
-
A union is similar to a structure in the way that it is declared and how its members are accessed, but there is a fundamental difference in the way storage is allocated:Originally posted by anarghyahow a structure is different from union?
structures: each member has its own area of storage
unions: the members use the same area of storage, i.e. they overlay each other. -
consider the code below,
#Code:#include<stdio.h> union koder { char c; int i; double d; }; main() { union koder new; printf("\n %d",sizeof(new)); }first code peice shows a union,when u print the size of the union it will give u the size of the largest member present in union .so at a time only any one member of the union can be accessedCode:#include<stdio.h union koder { char c; int i; double d; }; main() { union koder new; printf("\n %d",sizeof(new)); }
But in second case the size of the structure gives u ,the 16 bytes(with gcc obvious) This includes the padding considerations, so equall to sum of sizes of all the element present.Thus we can understand that in a structure we can all elements or a single element.Comment
Comment