In the following example try to find out difference between Structure & Union
structemp.c
main()
{
struct employee
{
int code;
char name[15];
}emp[2];
int i;
printf("Enter two Employee Details\n");
for(i=0;i<2;i++)
{
printf("Code:");
scanf("%d",&emp[i].code);
printf("Name:");
scanf("%s",emp[i].name);
}
printf("\nGiven Employee details are\n");
printf("Code\tName");
for(i=0;i<2;i++)
printf("\n%d\t%s",emp[i].code,emp[i].name);
}
For the above program, the output as follows
In the above program just replace the keyword struct with union and see what happen, the output as follows
while accepting there is no problem with the code, but while displaying it is displayed some garbage value. So this is not right example to highlight the importance of the union.
student_details.c
struct Dayscholar
{
int rollno;
char name[15];
char address[50];
char contactno[10];
};
struct Hostler
{
int rollno;
char name[15];
char contactno[10];
};
main()
{
union student_details
{
struct Dayscholar ds;
struct Hostler hs;
}student[5];
..........;
..........;
}
structemp.c
main()
{
struct employee
{
int code;
char name[15];
}emp[2];
int i;
printf("Enter two Employee Details\n");
for(i=0;i<2;i++)
{
printf("Code:");
scanf("%d",&emp[i].code);
printf("Name:");
scanf("%s",emp[i].name);
}
printf("\nGiven Employee details are\n");
printf("Code\tName");
for(i=0;i<2;i++)
printf("\n%d\t%s",emp[i].code,emp[i].name);
}
For the above program, the output as follows
In the above program just replace the keyword struct with union and see what happen, the output as follows
In this case, I try to explain this situation with an exact example, I want to maintain the two categories of student details one is Dayscholar and second one is Hostler. In Dayscholar, I can consider the members rollno, name, address, contactno. In Hostler, I can consider the members rollno, contactno. To maintain both details simultaneously, I can define two structures as globally and those structures used as reference members in the union which define the main function.
student_details.c
struct Dayscholar
{
int rollno;
char name[15];
char address[50];
char contactno[10];
};
struct Hostler
{
int rollno;
char name[15];
char contactno[10];
};
main()
{
union student_details
{
struct Dayscholar ds;
struct Hostler hs;
}student[5];
..........;
..........;
}
From the above program, it is possible to maintain 5 student details all are either Dayscholar or Hostler or mixed. Individually consider the size of the structure Dayscholoar is 2+15+50+10=77 bytes. and Hostler is 2+15+10=27. Because of we use the above structures as a reference in the union it will take the maximum size from the members. In this case, it is 77 bytes. With the help of 77 bytes, it is possible to maintain both categories of student details. If the union is not available both structures we can use separately, so that it will take 104 bytes. 27 bytes are reduced because of the union.
Comments
Post a Comment