Pointers
intermediateWhat you'll learn
- Explain what a memory address and a pointer are.
- Dereference a pointer and check it before use.
- Explain why a dangling pointer is undefined behavior.
A pointer stores the memory address of another variable. Pointers are powerful but require careful handling — they enable dynamic memory management, data structures, and low-level system programming.
Start With a Problem
A function must change the caller's variable. If it receives a copy, the caller's value never changes. Passing the variable's address lets the function reach the original:
To work with an address you need a type that stores one: a pointer. The rest of this note explains addresses, dereferencing, and safe use.
Use the hotel analogy: memory is a hotel of numbered rooms, a pointer is a slip of paper with a room number, and *p means 'go to that room'. A null pointer is a blank slip that names no room — it points to no object, and dereferencing it is undefined behavior.
Why Pointers Matter
- Dynamic memory allocation (new/delete)
- Efficient passing of large data structures
- Building data structures (linked lists, trees, graphs)
- Interfacing with operating systems and hardware
Declaring Pointers
The & Operator (Address-Of)
The * Operator (Dereference)
Memory Visualization
Null Pointer
Pointer Arithmetic
Common Mistakes
- Dereferencing null pointer: *nullptr (crash)
- Dangling pointer: p points to freed memory
- Uninitialized pointer: int* p; *p = 5; (wild pointer)
Never use an uninitialized pointer. Always set it to nullptr or point to a valid variable before dereferencing.
Key takeaway: Pointers store memory addresses — use & to get an address and * to dereference.
Try it: Declare an int and a pointer to it, print the value through the pointer, then change the value via *p and print the variable again to show they refer to the same memory.