Passing addresses to functions
What you'll learn: How to let a function modify a variable that lives outside of it by passing its memory address.
The problem with copies
Normally, when you pass a variable to a function, C makes a copy of that value. Imagine you have a physical document and you give someone a photocopy. If they take a red marker and scribble all over the photocopy, your original document remains clean.
In C, this is called "passing by value." It’s safe, but it means a function cannot change your original variables. To change the original, the function needs the "home address" of your data, not a copy of it.
Sharing the address
To let a function reach back into your main code and change a value, we use pointers. Instead of passing the variable itself, we pass the address of the variable (using the & operator). The function then uses a pointer to "go to" that address and update the value stored there.
Think of this like giving a mechanic the keys to your garage. They aren't working on a picture of your car; they are inside your property, changing the actual vehicle.
How it looks in code
In the example below, we want a function to "reset" a player's score to zero.
#include <stdio.h>
// The asterisk * means this function expects an address
void resetScore(int *scorePtr) {
*scorePtr = 0; // "Go to the address and set the value to 0"
}
int main() {
int myScore = 500;
// We pass the ADDRESS of myScore using &
resetScore(&myScore);
// myScore has been changed to 0!
printf("Current score: %d", myScore);
return 0;
}
Why this matters
We use this technique for two main reasons:
- Efficiency: If you have a massive piece of data, it’s much faster to pass a small address than to copy the entire data set.
- Multiple Results: A C function can usually only
returnone value. By passing multiple addresses, a function can "return" many different results by updating multiple variables at once.
Key takeaway
Passing an address (&variable) allows a function to modify the original variable instead of working on a temporary copy.