- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between Structure and Union in C
Structure
Structure is a user defined datatype. It is used to combine different types of data into a single type. It can have multiple members and structure variables. The keyword “struct” is used to define structures in C language. Structure members can be accessed by using dot(.) operator.
Here is the syntax of structures in C language,
struct structure_name { member definition; } structure_variables;
Here,
structure_name − Any name given to the structure.
member definition − Set of member variables.
structure_variable − This is the object of structure.
Here is an example of structures in C language,
Example
#include <stdio.h> #include <string.h> struct Data { int i; long int f; } data, data1; int main( ) { data.i = 28; printf("The value of i : %d\n", (data.i)); printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1)); return 0; }
Output
Here is the output
The value of i : 28 Memory size occupied by data : 16 16
Union
Union is also a user defined datatype. All the members of union share the same memory location. Size of union is decided by the size of largest member of union. If you want to use same memory location for two or more members, union is the best for that.
Unions are similar to the structure. Union variables are created in same manner as structure variables. The keyword “union” is used to define unions in C language.
Here is the syntax of unions in C language,
union union_name { member definition; } union_variables;
Here,
union_name − Any name given to the union.
member definition − Set of member variables.
union_variable − This is the object of union.
Here is an example of unions in C language,
Example
#include <stdio.h> #include <string.h> union Data { int i; float f; } data, data1; int main( ) { printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1)); return 0; }
Output
Here is the output
Memory size occupied by data : 4 4