Passing struct pointers to functions
What you'll learn: How to efficiently pass large structures to functions using pointers and the arrow operator.
The Mail vs. The House
Imagine you want a friend to help you renovate your kitchen. You have two choices: you can build an exact replica of your entire house and mail it to them (passing by value), or you can simply give them your address (passing by pointer).
In C, structures can be large. If a struct contains several arrays and strings, passing it directly to a function forces the computer to copy every single byte of that data onto the "stack." This wastes memory and slows down your program. Instead, we pass a pointer. This gives the function the "address" of the original data, allowing it to work on the structure directly without making a copy.
The Arrow Operator (->)
When you have a pointer to a struct, accessing its members looks a little different. While you could write (*ptr).member, that’s clunky. C provides a shortcut called the arrow operator (->). It literally means "follow this pointer to the struct and grab this variable."
#include <stdio.h>
struct Player {
char name[20];
int health;
};
// This function receives a pointer, not a copy
void levelUp(struct Player *p) {
p->health += 10; // Use -> to access members via pointer
printf("%s healed! New health: %d\n", p->name, p->health);
}
int main() {
struct Player hero = {"Aris", 50};
// Pass the address using the & operator
levelUp(&hero);
// The original 'hero' was actually modified
printf("Final health: %d\n", hero.health);
return 0;
}
Why This Matters
- Efficiency: A pointer is usually only 8 bytes, regardless of how huge the structure is.
- Persistence: Changes made inside the function stay changed. When you pass by value (the "mail" method), the function works on a temporary copy that vanishes when the function ends. By passing a pointer, you are handing the function the keys to the actual variable in memory.
Key takeaway
Passing a struct pointer is faster than passing the whole struct and allows a function to modify the original data using the -> operator.