$ ./pointers871#include <iostream>2int main() {3 int x = 5;4 int* p = &x;5 *p = 8;6 std::cout << x << '\n';7 int y = 7;8 p = &y;9 std::cout << *p << '\n';10 p = nullptr;11}0x1000x0x1004y0x1008p0x10000x100487!
Violet card: the program; each step lights the lines it runsBlue cells: memory, each with its address (top) and value (bottom)Wire: where p points · tokens: addresses and values on the moveIn front: the program pointers.cpp. On the right: three cells of memory, each with its address and value: x and y (ints, 4 bytes each) and the pointer p (8 bytes). At the back: the terminal. &x puts x's address into p, and a wire from p to x shows where p points. *p = 8 follows the wire and changes x. p = &y swings the wire to y, and *p then reads 7. p = nullptr removes the wire: p points nowhere, and following it is undefined behaviour. The addresses on the figure are made up and short so they fit. Real addresses are longer (on a 64-bit machine, something like 0x16fdff0bc), and most systems place a program at a different address every run. The compiler, not you, decides where x, y and p go and in what order; they may not sit side by side.

Addresses and pointers

  1. Line 3 makes an int called x. It needs 4 bytes of memory. Memory is a long row of bytes, and each byte has a number: its address. x starts at 0x1000, and holds 5.

Using a pointer

Null pointers

What happens

;; step 1/9 · address
3  int x = 5;
   x     an int: 4 bytes on this machine
   where at address 0x1000 (bytes 0x1000 to 0x1003)
   value 5
addresses here are made up and short; real ones are
longer, like 0x16fdff0bc, and change from run to run

The addresses on the figure are made up and short so they fit. Real addresses are longer (on a 64-bit machine, something like 0x16fdff0bc), and most systems place a program at a different address every run. The compiler, not you, decides where x, y and p go and in what order; they may not sit side by side. Sizes depend on the platform. The C++ standard only says int is at least 16 bits. On today's usual 64-bit systems (Linux, macOS, Windows) an int is 4 bytes and a pointer is 8; check with sizeof(int) and sizeof(int*).