The Dereference operator *
What you'll learn: How to use the asterisk symbol to access or modify the actual value stored at a specific memory address.
From Address to Value
In our previous lesson, we learned that a pointer is just a variable that holds a memory address—like a sticky note with a house address written on it. However, knowing the address is only half the battle. To actually see who lives inside the house or to change the furniture, you have to go to that location.
In C, we use the dereference operator, represented by the asterisk (*), to do exactly that. When you place a * in front of a pointer variable, you are telling the computer: "Don't give me the address; go to that address and give me the value stored there."
The "Remote Control" Analogy
Think of a pointer like a remote control for a television. The remote isn't the TV itself; it just holds a connection to it.
- The pointer is the remote.
- Dereferencing is like pressing a button on the remote.
When you "dereference" the remote, you change the actual TV's volume or channel. You aren't changing the remote; you are using the remote to affect the object it points to.
Seeing it in Code
Let’s look at how we use * to read and change a variable indirectly.
#include <stdio.h>
int main() {
int score = 10;
int *ptr = &score; // ptr now holds the address of score
// 1. Reading the value via dereferencing
printf("Value via pointer: %d\n", *ptr);
// 2. Modifying the value via dereferencing
*ptr = 20;
printf("New value of score: %d\n", score);
return 0;
}
In the example above, *ptr = 20 doesn't change the address stored in ptr. Instead, it follows the address to the score variable and overwrites the 10 with a 20.
One Symbol, Two Meanings
It is easy to get confused because * is used in two different ways. When you see int *ptr, the asterisk is just part of the type name, telling C that this variable is a pointer. However, when you see *ptr inside a regular line of code (an expression), it is the dereference operator acting as a "go to" command.
Key takeaway
Dereferencing a pointer with the * operator allows you to read or change the data at a specific memory address.