Structures and Unions
Grouping different types of data together under one name.
What is a Structure?
A struct lets you group variables of DIFFERENT types under one name — e.g. a Student struct might hold a name (char array), roll number (int), and marks (float) all together, unlike an array which only holds one type.
struct Student {
char name[50];
int rollNo;
float marks;
};
struct Student s1 = {"Rahul", 101, 89.5};
printf("%s", s1.name);Structures vs Unions
A struct allocates separate memory for EACH member, so all fields can hold values at the same time. A union shares the SAME memory location for all its members, so only one member can hold a valid value at any given time — useful for saving memory when you know only one field is needed at once.
Arrays of Structures
You can create an array of structs (struct Student classroom[30]) to represent a collection of records — like a whole classroom of students — each with their own name, roll number, and marks.
🌍 Real-World Use
A student database, an employee record system, or a simple inventory management program in C all use structures to bundle related fields (name, ID, price, quantity) together in one clean, organized unit.
💡 Pro Tip
In interviews, the classic question is 'struct vs union memory usage' — a struct's size is the SUM of all its members' sizes, but a union's size equals its LARGEST member's size, since members share the same memory space.
🧪 Quick Self-Test
Check what you just learned — no pressure, just practice.
1. In a struct, can all members hold valid values at the same time?
2. What determines a union's total size?