C++ ยท Chapter 25 of 49

C++ Pointers

A pointer is a variable that stores the memory address of another variable, declared with `*`. The `&` operator gets a variable's address, and `*` dereferences a pointer to access the value it points to.

Pointers are powerful but dangerous โ€” dereferencing a null or dangling pointer causes undefined behaviour, often a crash.

Declaring and dereferencing

`int x = 5; int* p = &x;` makes p store x's address. `*p` reads or writes the value at that address โ€” `*p = 10;` changes x to 10.

Null pointers

A pointer with no valid target should be set to `nullptr` (C++11). Always check `if (p != nullptr)` before dereferencing.

Example 1 (cpp)
int x = 5;
int* p = &x;
*p = 10;
std::cout << x;
Output
10

Dereferencing p and assigning changes x directly.

Example 2 (cpp)
int x = 42;
int* p = &x;
std::cout << *p;
Output
42

*p reads the value stored at the address p points to.

Key points

  • A pointer stores a memory address, declared with *.
  • & gets the address of a variable.
  • * dereferences a pointer to get/set its target value.
  • Uninitialised or dangling pointers should be set to nullptr.
๐Ÿ’ก Note: Modern C++ favours smart pointers (unique_ptr, shared_ptr) over raw pointers for managing ownership safely.

๐Ÿ“ Quick Quiz

1. Which operator gets the address of a variable?

2. Which operator accesses the value a pointer points to?

3. A pointer with no valid target should be set to: