A
structure is a collection of items of different types; and each data item will have its own memory location. Where as only one item within the
union can be used at any time, because the memory allocated for each item inside the union is in a
shared memory location i.e., only one memory location will be shared by the data items of union.
Size of union will be the size of the biggest variable.
Why do we need Union in the first place?Sometimes we may not need the data of all the (related) data items of a complex data structure and be storing/accessing only one data item at a time. Union helps in such scenarios.
e.g.,
typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;
typedef struct
{
float temp;
Condition feels_like;
} Temperature;
Wind Chill is only calculated when it is
cold and heat index is used only when it is
hot. There is no need for both of them at the same time. So when we specify the temp, feels_like will have only one value - either wind chill or heat index, but not both.
The following simple program illustrate the above explanation:
% cat structunion.c
#include <stdio.h>
#include <stdlib.h>
typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;
typedef struct
{
float temp;
Condition feels_like;
} Temperature;
void main()
{
Temperature *tmp;
tmp = (Temperature *)malloc(sizeof(Temperature));
printf("\nAddress of Temperature = %u", tmp);
printf("\nAddress of temp = %u, feels_like = %u", &(*tmp).temp, &(*tmp).feels_like);
printf("\nWind_Chill = %u, Heat_Index= %u\n", &((*tmp).feels_like).Wind_Chill, &((*tmp).feels_like).Heat_Index);
}
% cc -o structunion structunion.c
% ./structunion
Address of Temperature = 165496
Address of temp = 165496, feels_like = 165500
Wind_Chill = 165500, Heat_Index= 165500