Structures and Unions in C Pro
Structures and Unions in C Pro
a single name. They are essential for organizing complex data efficiently.
1. Structures in C
A structure (struct) is a collection of variables (of different types) grouped together under a single name.
It allows accessing and manipulating related data easily.
Syntax of Structure:
CopyEdit
struct structure_name {
data_type member1;
data_type member2;
...
};
Example of Structure:
CopyEdit
#include <stdio.h>
// Defining a structure
struct Student {
char name[50];
int age;
float marks;
};
int main() {
return 0;
Use the dot operator (.) with the structure variable to access members.
Pointer to Structure:
You can use pointers to access structure members using the arrow operator (->).
CopyEdit
Nested Structures:
CopyEdit
struct Address {
char city[30];
int pin;
};
struct Student {
char name[50];
};
Array of Structures:
CopyEdit
struct Student students[2] = {
};
Advantages of Structures:
Supports modular programming by defining data types once and reusing them.
2. Unions in C
A union is similar to a structure but with a crucial difference: all members share the same memory
location. This means only one member can store a value at any given time.
Syntax of Union:
CopyEdit
union union_name {
data_type member1;
data_type member2;
...
};
Example of Union:
CopyEdit
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
data.i = 10;
data.f = 3.14;
return 0;
CopyEdit
struct ExampleStruct {
int a; // 4 bytes
float b; // 4 bytes
};
union ExampleUnion {
int a;
float b;
char c;
};
Advantages of Unions:
Disadvantages of Unions:
Memory Allocates memory for all members separately. Shares memory for all members.
Data Handling All members can hold values simultaneously. Only one member holds a value at a time.
Usage Used for storing different data elements. Used when variables share memory.
Example Use Complex records (student info). Efficient memory use (flags, status).
Conclusion
Use structures when you need to store multiple data elements together.
Use unions when you need efficient memory management and mutually exclusive values.