BETA Try the new lesson view
Code

Passing by pointer

The third program: why functions need pointers.

CMakeLists.txt gets one more line:

add_executable(p08_pointers pointers.c)

pointers.c:

  • void swap(int *a, int *b) swaps the values of two variables through pointers. Contract: a and b aren't NULL.
  • void min_max(const int t[], int n, int *min, int *max) – two results from one call: it writes to *min and *max.
  • int sum(const int *t, int n) walks the array with a pointer: for (const int *p = t; p < t + n; p++). The loop ends when p reaches the address just past the last box.
  • main calls swap(&x, &y) and min_max(t, N, &min, &max): where the function writes, you pass the address.

Run it

p08_pointers and ▶:

Before: x = 3, y = 8
After:  x = 8, y = 3
Smallest: -2, largest: 9
Sum: 18

Forget the &

In main, write swap(x, y); instead of swap(&x, &y); and build:

error: passing argument 1 of 'swap' makes pointer from integer without a cast [-Werror=int-conversion]

The function expects an address and got an int. Without -Werror this would be only a warning, and the program would try to write to address 3 and crash. Undo it with Ctrl+Z.

Commit: Pass values by pointer.