Structs and typedef
Grouping related fields with struct, and giving struct types a clean name with typedef.
What you'll learn
- Define a struct type grouping several related fields
- Use typedef to give a struct type a shorter, reusable name
- Predict that assigning one struct variable to another copies all its fields by value
Explanation
A struct groups several related fields, possibly of different types, into a single custom type: struct Person { char name[20]; int age; };. You access a field with the dot operator: somePerson.age.
Writing struct Person every time you refer to the type gets verbose, so C offers typedef to give it a shorter alias. Combining a struct definition with typedef, typedef struct { char name[20]; int age; } Person;, lets you write just Person afterward instead of struct Person everywhere -- this is an extremely common pattern in real C codebases.
Like other C values, a struct is copied by value on assignment: Person carol = bob; copies every field of bob into a brand-new, independent carol -- changing carol.age afterward has no effect on bob.age at all. This is the same value semantics you've already seen for plain variables and function parameters, just applied to a type with multiple fields at once. Passing a struct to a function (by value, without a pointer) copies the whole thing the same way, which is worth remembering for larger structs where that copy has a real performance cost.
Guided lab
Predict: A typedef'd struct and value-copy assignment
Read this program and predict exactly what it prints.
#include <stdio.h>
typedef struct {
char name[20];
int age;
} Person;
void printPerson(Person p) {
printf("%s is %d years old\n", p.name, p.age);
}
int main(void) {
Person bob = {"Bob", 40};
printPerson(bob);
Person carol = bob;
carol.age = 41;
printf("bob age: %d, carol age: %d\n", bob.age, carol.age);
return 0;
}Stuck? Get a hint.
Common mistakes
- Forgetting to use the dot operator to access a struct field, e.g. writing `person.age` incorrectly or omitting it entirely.
- Assuming `Person carol = bob;` makes carol and bob share the same underlying data, instead of realizing it copies every field independently.
- Repeating `struct Person` everywhere instead of using typedef to introduce a shorter alias, which is idiomatic in real C code.
Knowledge check
Takeaway
typedef gives a struct a shorter, reusable name, and assigning one struct variable to another copies every field independently, just like plain variables.
Summary
struct groups related fields into one type, accessed with the dot operator; typedef gives it a shorter alias; struct assignment and pass-by-value both copy all fields.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.