
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
State the difference between structure and union with suitable example in C language
The differences between structures and unions in C language are explained below −
S.No | Structure | Union |
---|---|---|
1 |
Definition 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. |
2 |
Syntax;struct tagname{ datatype member1; datatype member2; ---- ---- ---- }; |
Syntax;union tagname{ datatype member1; datatype member2; ---- ---- ---- }; |
3 |
Eg;struct sample{ int a; float b; char c; }; |
Eg;union sample{ int a; float b; char c; }; |
4 | keyword − struct | keyword − union |
5 | Memory allocation | Memory allocation |
6 | ![]() |
![]() |
7 | Memory 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) |
8 | Memory 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
Advertisements