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)
// Pizza

Address 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.

ExpressionGives you
foodThe value (Pizza)
&foodThe address of food
ptrThe address stored in the pointer
*ptrThe value at that address (Pizza)

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.
Note: Only dereference a pointer that actually points to a valid variable. Dereferencing an uninitialized or null pointer causes your program to crash or behave unpredictably.