C++ Tutorial · Memory and Pointers · Lesson 10 of 21
C++ References and Pointers
Addresses, pointers, references, nullptr and when to use each.
Pointers
A pointer stores a memory address. &x gets the address; *p accesses the value:
#include <iostream>
int main() {
int score = 10;
int* p = &score; // pointer to score
int& ref = score; // reference (alias) to score
*p += 5;
ref *= 2;
std::cout << score << ' ' << *p << ' ' << ref << '\n';
std::cout << std::boolalpha << (p == &score) << '\n';
int* nothing = nullptr;
if (nothing == nullptr) std::cout << "pointer is null\n";
int arr[] = {10, 20, 30};
int* first = arr;
std::cout << *(first + 2) << '\n';
}
Output
30 30 30 true pointer is null 30
Run this on your computer — see “Get Started” for setup.
References
A reference is an alias for an existing variable. It must be initialised and can't be null or reseated — prefer references for function parameters.
Use nullptr (not NULL or 0) for a pointer that points nowhere, and always check before dereferencing.
Test yourself
Can a reference be null or be re-bound to another variable?
YesNoOnly const references
Show answer
Answer: No