Skip to content

Module 6 · Pointers and Memory — topic 3 of 5

Pointers and Functions

Passing pointers lets functions modify the caller's data and return multiple results; returning pointers needs care with lifetimes; function pointers let you pass behaviour as data, as qsort does.

Beginner 17 min read·Lesson 24 of 37 in C Programming

Learning objectives

  • Write functions that modify arguments through pointers
  • Return pointers safely
  • Declare and use function pointers, including with qsort

Definition

A pointer parameter receives a copy of an address, through which the function can access the caller's object (simulated pass-by-reference). A function pointer is a pointer whose type includes the function's parameter and return types, and through which the function can be called.

Introduction

Because C passes arguments by value, a function can't change the caller's variables directly. Pass their addresses instead, and the function can write through them. This is how scanf fills your variables and how a swap function works.

Functions themselves have addresses too. A function pointer lets you hand a function to another function — a callback. The standard qsort uses this to sort any type with a comparison function you supply.

Why it matters

Output parameters, swapping, in-place updates and returning several results all rely on pointer parameters.

Function pointers enable plug-in behaviour: sorting orders, event handlers, menu dispatch tables and state machines.

Detailed explanation

A parameter int *out receives an address; *out = value; stores into the caller's variable. The caller passes &variable.

Use const to document intent: void print(const int *a, int n) promises not to modify the array. const int *p is a pointer to const data; int *const p is a constant pointer to mutable data.

Returning a pointer is safe only if the object outlives the call: a static object, a heap allocation, or memory owned by the caller. Never return the address of a local (automatic) variable.

A function pointer declaration names the signature: int (*cmp)(const void *, const void *); — the parentheses around *cmp are required. Assign with cmp = compare_ints; and call with cmp(a, b).

qsort(base, count, size, cmp) sorts any array. cmp receives const void * pointers to two elements and returns negative, zero or positive.

Syntax

C
void swap(int *a, int *b); /* modifies caller's ints */
void min_max(const int *arr, int n, int *min, int *max);
int (*op)(int, int); /* pointer to function */
op = add;
int r = op(2, 3);
qsort(arr, n, sizeof arr[0], compare);
  • Pass &x for an int * parameter.
  • Without parentheses, int *f(int) declares a function returning int *.
  • A typedef makes function pointer types readable: typedef int (*BinOp)(int, int);.

Code examples

Swap through pointers

C
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main(void) {
int x = 1, y = 2;
swap(&x, &y);
printf("x=%d y=%d\n", x, y);
return 0;
}
Output
x=2 y=1

Returning two results

C
#include <stdio.h>
void min_max(const int *a, int n, int *min, int *max) {
*min = *max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *min) *min = a[i];
if (a[i] > *max) *max = a[i];
}
}
int main(void) {
int v[] = {42, 7, 19, 88, 3};
int lo, hi;
min_max(v, 5, &lo, &hi);
printf("min=%d max=%d\n", lo, hi);
return 0;
}
Output
min=3 max=88

More examples

Function pointers and qsort

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (*BinOp)(int, int);
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int asc(const void *a, const void *b) {
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y);
}
int by_name(const void *a, const void *b) {
const char *const *s = a, *const *t = b;
return strcmp(*s, *t);
}
int main(void) {
BinOp table[] = {add, sub, mul};
const char *names[] = {"add", "sub", "mul"};
for (int i = 0; i < 3; i++)
printf("%s(6, 3) = %d\n", names[i], table[i](6, 3));
int nums[] = {40, 5, 23, 5, 17};
qsort(nums, 5, sizeof nums[0], asc);
for (int i = 0; i < 5; i++) printf("%d ", nums[i]);
printf("\n");
const char *langs[] = {"Python", "C", "Java", "C++"};
qsort(langs, 4, sizeof langs[0], by_name);
for (int i = 0; i < 4; i++) printf("%s ", langs[i]);
printf("\n");
return 0;
}
Output
add(6, 3) = 9
sub(6, 3) = 3
mul(6, 3) = 18
5 5 17 23 40
C C++ Java Python

Step-by-step explanation

  • typedef int (*BinOp)(int, int); names the type “pointer to a function taking two ints and returning int”.
  • table is an array of function pointers — a dispatch table; table[i](6, 3) calls the i-th function.
  • asc converts its const void * arguments back to const int * and returns −1, 0 or 1 without risking overflow (unlike x - y).
  • For an array of strings, each element is a const char *, so the comparator receives pointers to those pointers.
  • qsort works on both arrays because it only needs the element size and the comparator.

Expected output

Running “Function pointers and qsort” prints exactly:

TextOutput
add(6, 3) = 9
sub(6, 3) = 3
mul(6, 3) = 18
5 5 17 23 40
C C++ Java Python

Practical applications

  • GUI toolkits register callbacks for button clicks.
  • Operating systems use tables of function pointers for device drivers.
  • qsort and bsearch from <stdlib.h> work on any data via comparators.

Best practices

  • Mark input-only pointer parameters const.
  • Document who owns memory a returned pointer refers to.
  • Use typedef for function pointer types.

Common mistakes

Passing a value where an address is needed

Avoid

int a = 1, b = 2;
swap(a, b);

Prefer

int a = 1, b = 2;
swap(&a, &b);

swap expects int *. Passing ints makes it treat 1 and 2 as addresses — a crash. The compiler warns.

Comparator that can overflow

Avoid

return *(const int *)a - *(const int *)b;

Prefer

int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y);

Subtracting large ints of opposite sign overflows (undefined behaviour) and gives the wrong order.

Important notes

  • A function name used as a value decays to a function pointer, so &add and add are equivalent.
  • Converting between function pointers and void * is not portable in ISO C, though POSIX systems allow it.

Key takeaways

  • Pass addresses to let functions modify caller variables.
  • Return pointers only to objects that outlive the function.
  • Function pointers enable callbacks such as qsort comparators.

Try it yourself

  1. 1
    Write void stats(const double *a, int n, double *mean, double *stddev).
  2. 2
    Sort an array of student structs by marks (descending) using qsort.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhy must `scanf` receive `&x` rather than `x`?
  • ModerateWhat is wrong with this function? `int *make(void) { int v = 42; return &v; }`
Practise this topic