C - Passing pointers to functions

Overview

Passing Pointers to Functions in C

Pass pointers when a function must modify caller-owned data or when you want to avoid copying large structures.

Learning Objectives

  • Pass pointers to allow in-place modification.
  • Understand pointer parameter contracts and nullability.

Prerequisites

Example

#include <stdio.h>

void increment(int *p) {
    if (p) { (*p)++; }
}

int main(void) {
    int x = 10;
    increment(&x);
    printf("x = %d\n", x);
}

Output: x = 11

Swap two numbers

#include <stdio.h>

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

int main(void) {
  int x = 5, y = 8;
  swap(&x, &y);
  printf("x = %d, y = %d\n", x, y);
}

Operate on arrays via pointer parameters

#include <stdio.h>

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

int main(void) {
  int nums[] = {1, 2, 3, 4};
  int n = (int)(sizeof nums / sizeof nums[0]);
  doubleArray(nums, n);
  for (int i = 0; i < n; i++) printf("%d ", nums[i]);
  printf("\n");
}

Common Pitfalls

  • Passing NULL and dereferencing without a check.
  • Forgetting that arrays decay to pointers; you must pass the length separately.

Checks for Understanding

  1. How do you modify a caller’s variable inside a function?
  2. Why must you pass the array length along with the pointer?
Show answers
  1. Pass its address and dereference inside: void f(int *p){ *p = ...; }
  2. Because the function only receives a pointer; it doesn’t know the array size.

Expected Output

x = 11
x = 8, y = 5
2 4 6 8 

Exercises

  1. Write void clamp(int *p, int min, int max) that clamps *p into [min, max].
  2. Implement void scale(int *arr, int n, int factor) to multiply each element by factor.