Skip to content

Pointers and References

Understanding direct memory access is what makes C++ powerful.

Pointers

A pointer is a variable that stores the memory address of another variable.

Declaration and Usage

  • & (Address-of operator): Get the address of a variable.
  • * (Dereference operator): Access the value at the address.
1
2
3
4
5
int value = 42;
int* ptr = &value; // ptr holds the address of value

std::cout << ptr;  // Prints address (e.g., 0x7ffee...)
std::cout << *ptr; // Prints 42

Null Pointer (nullptr)

Always initialize pointers. If you don't have a valid address, use nullptr.

int* ptr = nullptr;
// *ptr; // Undefined Behavior (Crash)

Void Pointers (void*)

A generic pointer that can point to any type. You must cast it back to the correct type to use it.

void* generic_ptr = &value;
int* int_ptr = static_cast<int*>(generic_ptr);

References

A reference is an alias for an existing variable. It must be initialized upon declaration and cannot be changed to refer to another variable.

1
2
3
4
int original = 100;
int& ref = original;

ref = 200; // original is now 200

Pointers vs. References

Feature Pointer (*) Reference (&)
Nullability Can be nullptr Must refer to a valid object
Reassignable Can point to different objects Bound for life
Initialization Optional (but dangerous) Required
Syntax Explicit dereferencing (*ptr) Transparent usage (ref)
Arithmetic Supported (ptr++) Not supported

Guideline: Use references by default. Use pointers only when you need nullability or pointer arithmetic.

[!IMPORTANT] Modern C++ Note: Raw pointers (*) should rarely be used for ownership (who deletes the memory). For managing resource lifetimes, always use Smart Pointers (std::unique_ptr, std::shared_ptr), which we will cover in Part 2. Raw pointers are fine for non-owning views.