Structure, Union & Typedef
Structures in C
Section titled “Structures in C”A structure in C is a collection of variables (called members) of different data types grouped together under one name.
Advantages of Structures:
- Handles complex data easily.
- Groups different data types logically.
- Useful in real-world applications like databases.
Disadvantages:
- Cannot directly compare two structures using ==.
- Takes more memory than arrays (because of padding).
Example
Section titled “Example”#include <stdio.h>#include <string.h>
struct Student { int roll; char name[50]; float marks;};
int main() { struct Student s; s.roll = 1; strcpy(s.name, "Akash"); s.marks = 92.5;
printf("Roll: %d\nName: %s\nMarks: %.2f\n", s.roll, s.name, s.marks); return 0;}
Roll: 1Name: AkashMarks: 92.50
Unions
Section titled “Unions”A union is similar to a structure but uses shared memory for all its members.
- Only one member can hold a value at a time.
- Size of union = size of largest member.
- memory = size of largest member.
Advantages of Union:
- Memory efficient (used in embedded systems).
- Useful for interpreting the same memory differently.
Disadvantages:
- Only one member can be used at a time.
- Risk of data overwrite.
Example
Section titled “Example”#include <stdio.h>
union Data { int i; float f; char str[20];};
int main() { union Data d; d.i = 10; printf("i: %d\n", d.i); d.f = 220.5; // overwrites i printf("f: %.2f\n", d.f); return 0;}
i: 10f: 220.50
Memory Layout:
- Structure: memory = sum of all members (with padding).
- Union: memory = size of largest member.
typedef in C
Section titled “typedef in C”typedef is used to create a new name (alias) for an existing data type.
Advantages of typedef:
- Makes code shorter and readable.
- Useful for portability (changing data types easily).
Example
Section titled “Example”#include <stdio.h>typedef unsigned int uint;typedef struct { int id; char name[50];} Student;int main() { uint age = 25; Student s = {101, "Shruti"}; printf("Age: %u, Name: %s\n", age, s.name); return 0;}
Age: 25, Name: Shruti
Real-World Applications:
- Structures – Database records (students, employees).
- Unions – Device drivers, protocol headers, embedded systems.
- typedef – Portable code for operating systems and libraries.