Skip to content
Justice Tech School

Pointers and Functions

To let a function change a variable, pass its address. The function receives a pointer and writes through it. Arrays are passed as pointers to their first element, which is why they can be modified inside functions.

Example
#include <stdio.h>

void swap(int *a, int *b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
}

void doubleAll(int arr[], int n) {
  for (int i = 0; i < n; i++) arr[i] *= 2;
}

int main(void) {
  int x = 1, y = 2;
  swap(&x, &y);
  printf("%d %d\n", x, y);
  int nums[3] = {1, 2, 3};
  doubleAll(nums, 3);
  printf("%d %d %d\n", nums[0], nums[1], nums[2]);
  return 0;
}

Result

2 1
2 4 6

Exercise

Pass the address of x.

swap(x, &y);

Quiz Test

Why does swap need pointers?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.