Nearby lessons
99 of 124C - Structure Introduction
A structure groups related variables of different types under one name. Learn why C needs them, how one struct replaces a fistful of parallel arrays, and where they sit alongside arrays and unions.
The Problem Structures Solve
Suppose you must store a student's name, roll number and marks. Without structures you need three separate variables — and three more for the next student:
Why Parallel Arrays Are Worse
The Structure Solution
An Array of Structures Cannot Drift
Swap two records and every member moves together. The bug from the parallel-array example simply cannot happen:
Structure vs Array
They answer different questions. "How many of the same thing?" is an array. "What parts make up one thing?" is a structure:
| Array | Structure | |
|---|---|---|
| Member types | All identical | Can differ |
| Access | By index: a[2] | By name: s.marks |
| Size | Fixed at declaration | Fixed by the definition |
| Assignable as a whole | No | Yes |
| Passed to a function | As a pointer (decays) | By value (copied) |
| Models | A list | A record |
Real-World Records
Almost anything you would put on a paper form maps onto a structure:
Structure vs Union
A structure gives each member its own storage. A union overlays them in the same bytes, so only one is valid at a time:
What Structures Give You
Beyond tidiness, a structure buys you four concrete abilities C does not otherwise have:
| Ability | Without structures | With structures |
|---|---|---|
| Copy a record | Member by member | b = a; |
| Pass a record | Many parameters | One parameter |
| Return a record | Impossible — use pointers | return s; |
| Store many records | Parallel arrays | One array of structs |
The Vocabulary
Four words appear constantly in structure code. Getting them straight now saves confusion later:
| Term | Meaning | Example |
|---|---|---|
| Tag | The name of the structure type | Student in struct Student |
| Member | One variable inside it | roll, marks |
| Definition | The blueprint — no memory yet | struct Student { ... }; |
| Variable | An actual instance with memory | struct Student s1; |
Common Mistakes
- Forgetting the
structkeyword — in C,Student s;alone is an error; usestruct Student s;or atypedef. - Missing the semicolon after
}— a structure definition ends with};. - Expecting
sizeofto be the sum of the members — padding usually makes it larger. - Comparing with
==— structures cannot be compared directly; compare member by member. - Confusing a definition with a variable — the definition allocates nothing.
- Reaching for a union to save space — a union only holds one member at a time.
- A structure holds several values of different types as one unit.
- An array holds many values of the SAME type; a structure holds different types.
- Members are accessed with the dot operator.
- A structure models a real-world record — a student, a book, a point.
- Every member gets its own memory, unlike a union.