Structure and Union in C
Structure and Union |
Both the structure and the union are user-defined data types which include variables of various data types. Both have the same description syntax, declaration variables and access to member.- There is a lot of difference still between company and community. We'll take a look at those variations in this tutorial.
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.
/* C Program to find difference between Structure and Union */
#include <stdio.h>
struct Employee
{
int age;
char Name[50];
char Department[20];
float Salary;
};
union Person
{
int ag;
char Nam[50];
char Departent[20];
float Salar;
};
int main()
{
struct Employee emp1;
union Person Person1;
printf(" The Size of Employee Structure = %d\n", sizeof (emp1) );
printf(" The Size of Person Union = %d\n", sizeof (Person1));
return 0;
}
Expected Output
The Size of Employee Structure =72
The Size of Person Union =50