C++ Pointers

A pointer is a variable that stores the memory address of another variable, rather than a value directly. Pointers are a powerful feature of C++ that let you work with memory addresses, and they are the foundation for many advanced techniques.

Memory Addresses

Every variable your program creates lives at a location in memory. You can see that location, called its address, by placing the ampersand (&) operator in front of the variable name.

Printing a variable's address

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Pizza";
  cout << food << "\n";   // the value
  cout << &food;          // the memory address
  return 0;
}
// Output:
// Pizza
// 0x61ff08 (address will vary)

Creating a Pointer

You declare a pointer with a star (*) between the type and the name. The pointer's type must match the type of the variable whose address it stores. Then you store an address in it using the & operator.

A pointer that holds an address

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Pizza";
  string* ptr = &food;   // ptr stores the address of food
  cout << food << "\n";  // prints the value
  cout << &food << "\n"; // prints the address
  cout << ptr;           // prints the same address
  return 0;
}

Why Use Pointers?

  • They let functions change the caller's data instead of working on a copy.
  • They are used to build dynamic data structures like linked lists and trees.
  • They allow you to manage memory that is created while the program runs.
SymbolNameMeaning
&Address-of operatorGives the memory address of a variable
*In a declarationMarks the variable as a pointer
*Before a pointerDereferences, giving the stored value
Note: The star (*) means different things depending on where it appears. In a declaration it creates a pointer; in front of an existing pointer it fetches the value at that address. We will explore the second use in dereferencing.

Exercise: C++ Pointers

What does the & operator do when applied to a variable?