Structs & typedef
Bundling related data into one type, and how the -> operator reads through a struct pointer
In a nutshell
A struct is C’s mechanism for putting several related fields into one type. The closest Java analogue is a plain old data class (no methods, just fields). typedef lets you give the struct type a short name so you can write Student s; instead of struct Student s;. Access a field with dot notation (s.name) on a struct value, or arrow notation (p->name) on a struct pointer — p->name is exactly (*p).name, just shorter.
Why it matters
Every non-trivial C program groups related data. Network packets, database rows, student records, game entities — all of them become structs. Once you have structs, you can have arrays of structs (the practical organization for any list of records) and you can start writing data structures (linked lists, trees, hash tables) whose nodes are structs holding pointers to other nodes.
Key takeaways
structdeclares a new type. The full form isstruct Student { char name[50]; int age; double gpa; };.typedefgives it a short name.typedef struct { ... } Student;lets you writeStudent s;.- Dot on values, arrow on pointers.
s.ageandp->age.p->ageis shorthand for(*p).age. - Structs are passed by value by default. Passing a large struct copies every field. Use
const Student *for read-only access; useStudent *when the function should modify the caller’s struct. - Alignment and padding exist. The compiler inserts unused bytes inside a struct to keep fields on natural alignment boundaries.
sizeof(Student)is usually larger than the sum of the field sizes. - Arrays of structs are the usual way to hold a collection:
Student roster[50];.
Lessons in this topic
| Lesson | What it covers |
|---|---|
| Structs & typedef | Declaring struct types, typedef shorthand, accessing fields, arrays of structs |
| Struct Pointers | The -> operator, passing structs by pointer, modifying struct fields from a function |
Practice and deep dives
Practice this topic: Structs drill, or browse the practice gallery.
What comes next
Arrays of Structs & Sorting — building a roster of students, sorting it by any field, and the search patterns you will see in every data-processing program.