← 🔁 Functions & Recursion
Subtopic 2 of 5

5.2Call by reference with pointers

The idea

To let a function change a caller's variable you pass its address and write through the pointer.

Think of it like this: Instead of a photocopy you give the person the address of your original file cabinet.

Why it exists

Almost every "what is printed" question about pointers to ints, arrays and structs reduces to this.

How it works

  1. Caller passes &a (or an array name).
  2. The function receives the address in a pointer parameter p.
  3. *p = x writes into the caller's variable.
  4. Reassigning p itself only changes the function's copy of the address.

Worked example: foo(z, b) with z = &a

*p = x stores 25 into the location p points to, which is a. main prints 25.

Now play with it

  • →Step through change through a pointer and see a change inside foo.
  • →In reassigning the pointer is invisible, notice a and *q stay 1.

z holds the address of a, so foo(z, b) writes b into a through p.

step 1 of 8
1#include <stdio.h>
2void foo(int *p, int x) {
3 *p = x;
4}
5int main() {
6 int *z;
7 int a = 20, b = 25;
8 z = &a;
9 foo(z, b);
10 printf("%d", a);
11 return 0;
12}

The gold line is the statement about to run.

Call stack (top first)
main()
no variables yet
Output

Check yourself

void f(int *p) { *p = 5; p = 0; } Called as f(&n). What is n afterwards?

Remember: *p = … reaches the caller; p = … does not. Arrays are passed by address.
Exam notes (the dense version)

To let a function change the caller's variable pass its address and write through it: void foo(int *p, int x) { *p = x; }. The pointer itself is still passed by value, so reassigning p inside the function is invisible outside, while *p = … is visible. Arrays are passed as a pointer to the first element, so changes to elements are visible.

Previous year questions: Functions & Recursion (11)

PYQs are grouped by topic, so this is the full set for Functions & Recursion; try the ones that match this subtopic. Open all 11 on the topic page.