CP C++

C++: Pointers & References

What you will learn

Pointers store memory addresses; references are aliases. Both let you work with data indirectly, but they behave differently.

Pointers

A pointer holds the memory address of another variable. Declare with *:

int x = 10;
int* ptr = &x;    // ptr stores the address of x

std::cout << ptr;   // prints the address (e.g., 0x7ffeef)
std::cout << *ptr;  // dereference — prints 10 (the VALUE at the address)
  • &x takes the address of x (returns a pointer)
  • *ptr dereferences the pointer (follows the address to get the value)
  • nullptr is the modern null pointer (use instead of NULL or 0)
int* p = nullptr;  // safe null pointer
if (p != nullptr) {
    std::cout << *p;
}

References

A reference is an alias — another name for an existing variable. Declare with &:

int x = 10;
int& ref = x;    // ref is a reference (alias) to x
ref = 20;         // x is now 20

std::cout << x;    // 20
std::cout << ref;  // 20

Unlike pointers, references: - Must be initialized when declared (cannot be null) - Cannot be reassigned to refer to a different variable - Are used with dot notation (no dereferencing)

Pointers vs References — when to use what

Use Case Pointer Reference
Can be null Yes (use nullptr) No
Can be reassigned Yes No
Syntax to access value *ptr (dereference) ref (direct)
Use in function parameters When "no object" is valid When object must always exist

Common mistakes

  • Dereferencing a null or uninitialized pointer — causes undefined behavior (crash)
  • Confusing int* p (pointer to int) with int& p (reference to int)
  • Forgetting & when passing to a pointer parameter: func(&x) not func(x)
  • Declaring a reference without initializing it — compile error

Quick check below!