Pointers to Structures & Self-Reference
Most real C code passes structures by pointer. The arrow operator is the shorthand that makes this readable.
In plain English
A struct pointer is a note with the form's address, so you can edit the form without copying it.
Pointers to structures and the -> operator
When you have a pointer to a structure, p->member is shorthand for (*p).member. This is the normal way to traverse linked structures and to avoid copying large records into functions. Pass a pointer when a function should modify the original; pass the structure by value when a copy is acceptable.
struct Student {
int id;
double gpa;
};
void promote(struct Student *s) {
s->gpa += 0.1; /* same as (*s).gpa += 0.1 */
}
struct Student s = {1, 3.9};
promote(&s);
printf("%.1f\n", s.gpa); /* 4.0 */Self-referential structures
A self-referential structure contains a pointer to its own type. This is how linked lists, trees, and graphs are built. A structure cannot contain an instance of itself because that would require infinite storage, but a pointer has a fixed size. A linked node typically stores a value and a next pointer.
struct Node {
int value;
struct Node *next; /* self-referential */
};
struct Node second = {2, NULL};
struct Node first = {1, &second};
printf("%d\n", first.next->value); /* 2 */Key takeaways
- p->member is equivalent to (*p).member.
- Passing a structure by pointer avoids copying and allows mutation.
- A self-referential structure stores a pointer to its own type.
- Linked lists and trees are built from self-referential nodes.
Common pitfalls
- Using . on a pointer instead of ->.
- Trying to put an instance of a struct inside itself.
- Forgetting to initialize the next pointer to NULL.
Key focus
- Trace member access through pointers and linked nodes.
- Know the difference between -> and (*p).member.
Quick check
1. If p is a pointer to struct Node, which expression accesses member value?
2. Why can a structure contain a pointer to its own type but not an instance of itself?