Difference between Structure and Union
Structure and union both are user defined data types which contains variables of different data types. Both of them have same syntax for definition, declaration of variables and for accessing members. Still there are many difference between structure and union. In this tutorial we will take a look on those differences.
Difference between Structure and Union
Structure Union
In structure each member get separate space in memory. Take below example.
struct student { int rollno; char gender; float marks; }s1;
The total memory required to store a structure variable is equal to the sum of size of all the members. In above case 7 bytes (2+1+4) will be required to store structure variable s1.
In union, the total memory space allocated is equal to the member with largest size. All other members share the same memory space. This is the biggest difference between structure and union.
union student { int rollno; char gender; float marks; }s1;
In above example variable marks is of float type and have largest size (4 bytes). So the total memory required to store union variable s1 is 4 bytes.
We can access any member in any sequence.
s1.rollno = 20; s1.marks = 90.0; printf("%d",s1.rollno);
The above code will work fine but will show erroneous output in the case of union. We can access only that variable whose value is recently stored.
s1.rollno = 20; s1.marks = 90.0; printf("%d",s1.rollno);
The above code will show erroneous output. The value of rollno is lost as most recently we have stored value in marks. This is because all the members share same memory space.
All the members can be initialized while declaring the variable of structure. Only first member can be initialized while declaring the variable of union. In above example we can initialize only variable rollno at the time of declaration of variable.