Assigning values via pointers
What you'll learn: How to change the data stored in a variable by using its memory address instead of its name.
The Remote Control Analogy
In our previous lessons, we learned that a pointer is like a piece of paper with a house address written on it. Simply looking at the address tells you where the house is, but it doesn't change the color of the front door.
To actually change something inside that house, you need to use the dereference operator (*). Think of this symbol as a remote control. When you place the * in front of a pointer’s name, you aren't talking to the pointer anymore; you are talking to the variable it is pointing at.
Using the Dereference Operator
When you want to assign a new value to a variable through a pointer, you follow a specific syntax: *pointer_name = new_value;.
This tells the computer: "Go to the address stored in this pointer, walk inside, and replace whatever data is there with this new data."
#include <stdio.h>
int main() {
int goldCoins = 50; // Our original variable
int *ptr = &goldCoins; // ptr now holds the address of goldCoins
printf("Coins before: %d\n", goldCoins);
// We use the '*' to access the value at the address
// This line changes goldCoins to 100
*ptr = 100;
printf("Coins after: %d\n", goldCoins);
return 0;
}
Why does this matter?
You might wonder: "Why not just write goldCoins = 100?" In a simple program, you would. However, as you advance, you will encounter situations where your code doesn't have direct access to a variable's name—perhaps the variable belongs to a different part of the program entirely.
By passing a pointer (the address), you give that other part of the program a "remote control" to update your data. It is a powerful way to share and modify information across your code without making unnecessary copies of your data.
Key takeaway
Placing the * operator before a pointer name during an assignment allows you to modify the value stored at that memory address.