Nearby lessons
98 of 124C - Structures
Structures is one of the foundational topics in C programming. This lesson explains Why Structures?, Defining a Structure and Program 1: Declare Variables and Access Members with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Why Structures?
Arrays hold many values of the same type. But a student has a name (string), a roll number (int), and marks (float) — different types. A structure groups these different types under one name.
Think of a structure as a form: the Student form has one box for name, one for roll number, one for marks — all carried together as one unit.
Defining a Structure
This only creates a template (a design). It does not reserve memory. Memory is reserved when we declare variables of this type.
Program 1: Declare Variables and Access Members
The dot operator (.) is how you reach a member. It is also called the member access operator.
Program 2: Initializing in One Line
Program 3: Take a Student's Data from the User
Structure vs Array — One-Line Memory
| Point | Array | Structure |
|---|---|---|
| Members | Same type | Can be different types |
| Access | With index a[0] | With member s.name |
| Use for | A list of similar values | A record with mixed fields |
- Structure groups different types under one name — like a form.
- Define the template, declare variables, access members with the dot.
- Separate programs: access, one-line init, user input, arrays of structures.
- Structures can nest inside structures.
- Union shares one memory for all members; structure gives each member its own.
- sizeof(union) = largest member; sizeof(struct) = sum of members.