Loading lessons...
Structures and Pointers
Structures and Pointers
Pointers work with structs too, and that's how functions can modify them.
A pointer to a struct
struct Person p1 = {"Ada", 36, 1.7};
struct Person *pp = &p1;
Access members with ->
When you have a pointer, use the arrow operator ->:
printf("%s\n", pp->name);
pp->age = 37;
pp->age is the same as (*pp).age.
Why pass pointers?
Functions receive structs efficiently by pointer and can modify the original:
void birthday(struct Person *p) {
p->age++;
}
Dot vs arrow
- Dot
.for a struct variable. - Arrow
->for a pointer to a struct.
TL;DR
- Pointers can point to structs.
- Use
->to access members through a pointer. pp->ageequals(*pp).age.- Passing pointers lets functions change the struct.