Site icon i2tutorials

Difference between union and structure

Difference between union and structure

 

Though unions are similar to the structure in so many ways, the difference between them is crucial to understand.

 

StructureUnion
1.The struct keyword is used for the definition of a structure.

 

1. The keyword union defines a union.
2. When a variable is attached to a structure, the compiler assigns memory to each member. The size of the structure is larger or equal to the sum of the members’ sizes. Shorter members can end up with unused bytes.

 

2. When a variable is associated with a union, the compiler allocates the memory taking into account the size of the greatest memory. This means that the size of the union is equal to the size of the largest member.
3. Each member of a structure receives a single storage area.

 

3. The memory assigned is shared by every union member.
4. The address of each member will be in ascending order This indicates what memory for each member will begin at different offset values.

 

4. All union members have the same address. This indicates that each member is starting at the same offset.
5.Changing the value of one member will not impact other members of the structure.

 

5. Modifying the value of any of the members will modify the other values of the members.

 

6. The individual members of the Structure are accessible to each other.

 

6. Only one member of the Union shall be accessible at any one time.

 

7. Several members of a structure can be initialized together.

 

7. You can only initiate a single member of a union.

 

 

The primary difference can be demonstrated by this example:

 

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
return 0;
}

 

Output:

 

 

More memory is allotted to the structures than to the union.

As the above example illustrates, there is a difference in memory allocation between the union and structure.

The amount of memory needed to store a structure variable is the sum of the total memory size of all members.

 

 

But, the memory required to store a union variable is the memory required for the most significant part of a union.

 

 

Example Program with Structures & Union:

 

#include<stdio.h>
struct number1
{
int i;
float f;
char c;
}sn;
union number2
{
int i;
float f;
char c;
}un;
void main()
{
printf("Details of structure\n");
printf("size of structure number1=%d\n",sizeof(sn));
sn.i=10;
sn.f=89.00;
sn.c='X';
printf("sn.i=%d\n sn.f=%f\n sn.c=%c\n",sn.i,sn.f,sn.c);
printf("Details of Union\n");
printf("size of Union number2=%d\n",sizeof(un));
un.i=10;
un.f=89.00;
un.c='X';
printf("un.i=%d\n un.f=%f\n un.c=%c\n",un.i,un.f,un.c);
}

 

Output:

 

 

Exit mobile version