Skip to the page

Pointers and memory · core

Pointers, references and passing arguments

A pointer holds an address; a reference is another name for an existing variable. Pass by value gives the function a copy; pass by pointer or by reference lets it change the caller's variable.

The notes

What you must know

  • A pointer is a variable that holds an address: int* p = &x;, and *p reads or changes x. It can be null, and it can later point somewhere else.
  • A reference is another name for an existing variable: int& r = x;. It must be set when it is created, it cannot be made to refer to something else later, and there is no null reference.
  • Use nullptr (C++11), not NULL or 0, for a pointer that points to nothing. Dereferencing a null pointer is undefined behaviour and usually crashes.
  • Read const from right to left: const int* p is a pointer to a const int (you cannot change *p, but p can move). int* const p is a const pointer (p cannot move, but *p can change).
  • Call by value: the function gets a copy, so swap(int a, int b) changes nothing outside. Call by pointer: pass &x and change *a. Call by reference: swap(int& a, int& b) changes the caller's variables.
  • Pass a big object as const T&: no copy is made, and the function promises not to change it. Passing a vector by value copies all n elements on every call.
  • Never return a reference or a pointer to a local variable: the local dies when the function returns, so the reference dangles. Dangling: points to memory that is gone. Wild: never initialised.
  • Rule from the C++ FAQ: use references when you can, and pointers when you have to, for example when "no object" (nullptr) is a valid value or the target must change.

The red pen

Common traps: mistake → fix

  • Mistake: A reference is a pointer with nicer syntax and can be null

    Fix: a valid reference always refers to an object and cannot be reseated.

  • Mistake: const int* p means p cannot change

    Fix: it means p cannot change; int const p fixes p.

  • Mistake: swap(int a, int b) swaps the caller's variables

    Fix: it swaps its own copies.

  • Mistake: Passing a vector by value is free

    Fix: it copies every element.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between a pointer and a reference?
  2. What does this program print? (swap by value, by pointer and by reference)
  3. What is the difference between const int* p and int* const p?
  4. Why pass a big object as const Student&?
  5. A recursive DFS passes the graph by value and gets Time Limit Exceeded. Why?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview