Pointer Basics

Every variable is stored somewhere in the computer's memory. Each place in memory has a number, called its address. A pointer is a variable that holds an address. You can think of the address as a house number, and the pointer as a note with that house number written on it.

Two operators work with pointers:

  • &x gives the address of the variable x
  • *p gives the value stored at the address inside p
#include <iostream>
using namespace std;

int main() {
    int stock = 12;
    int* p = &stock;
    cout << *p << "\n";
    *p = 8;
    cout << stock << "\n";
    return 0;
}

Output:

12
8

int* p creates a pointer to an int. &stock is the address of stock, so now p points to stock. Reading *p goes to that address and finds 12. The line *p = 8 writes 8 at that address, so stock really is 8 afterwards.

The signs * and & have two jobs, so look at where they stand. In a type, like int* p or int& r, the sign is part of the type: a pointer or a reference. In front of a variable, like *p or &stock, it is an operator: "the value at" or "the address of".

   stock                  p
  +--------+         +-----------+
  |   12   | <------ | &stock    |
  +--------+         +-----------+
  the value          the address

If you print the pointer itself, you see the address:

cout << p << "\n";

One run printed this:

0x7ffe9ffc21f4

This is a number written in hexadecimal (base 16). You will see a different number each time you run the program, because the system places the program's memory at a different spot each time. The address itself is rarely useful to print. What matters is the value it leads to.

A pointer can move

A reference, from the References lesson, always stays with the same variable. A pointer is different: you can point it at another variable later.

int a = 1;
int b = 2;
int* p = &a;
cout << *p << "\n";
p = &b;
cout << *p << "\n";

Output:

1
2

Pointing to nothing

A pointer can also point to nothing. The value for that is nullptr. Reading through a null pointer is a serious bug. The program crashes:

#include <iostream>
using namespace std;

int main() {
    int* q = nullptr;
    cout << "Before" << "\n";
    cout << *q << "\n";
    cout << "After" << "\n";
    return 0;
}

Output:

Before

Before printed, and then the program crashed with a Segmentation fault error. This means the program tried to use memory it is not allowed to use. After never printed. If a pointer might be nullptr, check it with if (q != nullptr) before you use *q.

In the exercise, point a pointer at a price. The program then reads and changes the price through it.