State the difference between structure and union with suitable example in C language

CServer Side ProgrammingProgramming

The differences between structures and unions in C language are explained below −

S.NoStructureUnion
1Definition
Structure is heterogenous collection of data items grouped together under a single name
Definition
A union is a memory location that is shared by several variables of different datatypes.
2Syntax;
struct tagname{
   datatype member1;
   datatype member2;
   ----
   ----
   ----
};
Syntax;
union tagname{
   datatype member1;
   datatype member2;
   ----
   ----
   ----
};
3Eg;
struct sample{
   int a;
   float b;
   char c;
};
Eg;
union sample{
   int a;
   float b;
   char c;
};
4keyword − structkeyword − union
5Memory allocationMemory allocation
6
7Memory allocated is the sum of sizes of all datatypes in structure(Here, 7bytes)
Memory allocated is the maximum size allocated among all the datatypes in union(Here, 4bytes)
8Memory is allocated for all the members of the structure differently
Only one member will be residing in the memory at any particular instance

Example

Following is the C program for structures −

#include<stdio.h>
struct size{
   double a;
   int b;
   char c;
   float d;
};
int main(){
   printf("%ld",sizeof( stuct size));
}

Output

When the above program is executed, it produces the following result −

24

Example

Following is the C program on union −

#include<stdio.h>
union size{
   double a;
   int b;
   char c;
   float d;
}
Int main(){
   Printf("ld",sizeof(union size));
}

Output

When the above program is executed, it produces the following result −

8
raja
Published on 09-Mar-2021 08:40:15
Advertisements