Program to show difference between "Structure and Union".

Difference between "Structure and Union"
Structure and Union

S.no
C Structure
C Union
1
Structure allocates storage space for all its members separately.
Union allocates one common storage space for all its members.
Union finds that which of its member needs high storage space over other members and allocates that much space
2
Structure occupies higher memory space.
Union occupies lower memory space over structure.
3
We can access all members of structure at a time.
We can access only one member of union at a time.
4
Structure example:
struct student
{
int mark;
char name[6];
double average;
};
Union example:
union student
{
int mark;
char name[6];
double average;
};
 5
For above structure, memory allocation will be like below.
int mark – 2B
char name[6] – 6B
double average – 8B
Total memory allocation = 2+6+8 = 16 Bytes
For above union, only 8 bytes of memory will be allocated since double data type will occupy maximum space of memory over other data types.
Total memory allocation = 8 Bytes

/*C program to show difference between Structure and Union*/

#include <stdio.h>
union job              //defining a union
{         
   char name[32];
   float salary;
   int worker_no;
}u;
struct job1            //defining a structure
{       
   char name[32];
   float salary;
   int worker_no;
}s;
int main()
{
   printf("size of union = %d",sizeof(u));
   printf("\nsize of structure = %d", sizeof(s));
   return 0;
}
Expected Output:

size of union = 32
size of structure = 38

Post a Comment

Previous Post Next Post