It is very important to understand the difference between structure and union because it is the one and the only thing that differs both of them from each other. Let’s see a Program before going into the theory part.
Table of Contents
Program
#include<stdio.h> struct Item1 { int numeric; char alpha[20]; float decimal; }; union Item2 { int numeric; char alpha[20]; float decimal; }; int main() { struct Item1 X; union Item2 Y; printf("size of structure =%d\n",sizeof(X)); printf("size of union =%d\n",sizeof(Y)); return 0; }
Output
Explanation
The above program output shows the difference between structure and union, i.e., their sizes.
In the Program written above, members of both structure and union are the same, but the size of the structure we obtained is 28, and the size of the union we obtained is 20.
In the structure, the sum of the memory sizes of all its members is the amount of memory required to store it. Three members of the structure are numeric, alpha, and decimal. Since numeric and decimal are of type ‘int’ and ‘float’ respectively thus, their size is 4 bytes each, alpha is of type ‘char’ with array size 20, and thus its size becomes 20.
Therefore, the sum of the members’ sizes is 4+4+20=28 bytes.
In union, the memory size will equal the member’s size occupying the maximum space in the memory. We have 3 members of the union that are numeric, alpha, and decimal of type int, char, and float, respectively. Since the size of numeric and decimal is 4 bytes each and the alpha size is 20 bytes (20* size of char=20*1=20).
Therefore, the space occupied by the union is 20 bytes.
Memory allocated to structure:
Memory allocated to union:
Thus, we can access only one union member at a time because there is only one memory block allocated to the union of the size equal to the maximum size of its member. As a result, we can use only one union member at a time.
Rest all the other members will contain some garbage value.
On the other hand, there is no such limitation of accessing one member at a time.
Different memory spaces are allocated to each member of the structure. Thus, we can access all the members simultaneously.
0 Comments