Learn C++ · lesson 34 of 61 · about 8 minutes
Pointers
Pick up a weapon in the armoury: store addresses in pointers, follow them with *, and know when a pointer is empty.
What you'll learn
- Take an address with &
- Read and write through a pointer
- Use nullptr for 'points nowhere'
The armoury
Below the castle, the hero finds an armoury with a sword (12 damage) and an axe (18). The hero types which one to pick up, and an int* weapon points at that one: weapon = &axe;. A whetstone sharpens whatever the hero holds with *weapon += 3;, which changes the axe itself, because weapon holds the axe's address. If the hero asks for something that isn't there, weapon stays nullptr, and the adventure checks for that before following it.
Addresses
Every variable lives at an address in memory.
&xis the address of xint* p = &x;stores it in a pointer*pfollows the pointer to the valuenullptrmeans "points to nothing"; never follow it
A reference (int& r = x;) is another name that can never be empty or re-pointed. A pointer can be null and can be changed to point elsewhere.
Through a pointer
#include <iostream>
int main() {
int coins = 50;
int* p = &coins;
*p = 75;
std::cout << coins << " " << *p << " " << (p == &coins) << "\n";
int gems = 3;
p = &gems;
*p += 1;
std::cout << coins << " " << gems << "\n";
int* empty = nullptr;
if (empty == nullptr) std::cout << "points nowhere\n";
}Output
75 75 1
75 4
points nowhereTip
In modern C++ you'll mostly use references, containers and smart pointers. Raw pointers are still everywhere in older code and libraries, so it pays to understand them.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.