For updating memory
Your assignment copies content from a structure, but there are still two distinct structures:
#include<stdio.h>
typedef struct {
int health;
} Boss;
int main() {
Boss bigBoss;
bigBoss.health = 40;
Boss newBoss;
newBoss.health = 100;
bigBoss = newBoss;
bigBoss.health = 1;
newBoss.health = 2;
printf("%d %d\n", bigBoss.health, newBoss.health);
}
1 2
That copying behavior is the same that you get when you pass a structure to a function directly. If you pass a Boss
to a function and try to modify it, you'll be modifying the copy that's local to that function, not the original Boss
. If you pass a pointer to the Boss
instead, then you can modify the contents of the original Boss
. For instance:
#include<stdio.h>
typedef struct {
int health;
} Boss;
void fail_attack( Boss boss ) {
boss.health -= 10;
}
void succeed_attack( Boss *boss ) {
boss->health -= 10;
}
int main() {
Boss bigBoss;
bigBoss.health = 40;
fail_attack( bigBoss );
printf( "after fail_attack, health: %d\n", bigBoss.health );
succeed_attack( &bigBoss );
printf( "after succeed_attack, after succeed_attack, health: %d\n", bigBoss.health );
}
after fail_attack, health: 40
after succeed_attack, health: 30
To reduce the cost of parameter passing
Even when you don't need this modification behavior, passing a pointer still saves space because you don't have to copy the entire structure, but rather just a pointer. For a structure with just one integer field, this isn't a big difference, if a difference at all, but for structures with multiple fields, this is important.
For self referential types
A instance of a structure is really just a blob of memory populated by the fields declared in the structure. How big is the blob of memory? Well, it needs to be at least big enough to hold the fields, and possibly a bit bigger for memory alignment. Some data structures that hold references to other instances of the same data structure (e.g., linked lists and trees are some of the earliest encountered data structures). How big would a linked list node need to be to hold an element and a next node? Well, size(node) = size(element) + size(node). That clearly won't work. On the other hand, a pointer is a fixed size, so we can have a node that has an element and a pointer to another node.