C++ Dereferencing
Getting the memory address is useful, but often you want the actual value stored at that address. Dereferencing lets you follow a pointer to the value it points to, using the star (*) operator.
The Dereference Operator
When you place a star (*) in front of a pointer, C++ goes to the address stored in the pointer and gives you the value living there. People often say you are following the pointer.
Getting the value behind a pointer
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
string* ptr = &food;
cout << ptr << "\n"; // the address
cout << *ptr; // the value at that address
return 0;
}
// Output:
// 0x61ff08 (varies)
// PizzaAddress Versus Value
It helps to keep the two ideas separate. Writing ptr on its own gives the address the pointer holds. Writing *ptr gives the value stored at that address. Mixing these up is a very common beginner mistake.
Reading Through a Pointer
Once you have a pointer, dereferencing lets you use the value just like the original variable. Here we work with an integer to show the same idea applies to any type.
Dereferencing an int pointer
#include <iostream>
using namespace std;
int main() {
int score = 95;
int* ptr = &score;
cout << "Value: " << *ptr << "\n";
cout << "Doubled: " << (*ptr * 2);
return 0;
}
// Output:
// Value: 95
// Doubled: 190- Use * to read the value a pointer refers to.
- The pointer itself still just holds an address.
- Dereferencing works for any type, not only strings or ints.