← C roadmap

Topic 12 of 15 · Advanced

Function Pointers & Callbacks

Pointers to functions, qsort and arrays of pointers.

Concept

A function pointer stores the address of a function so it can be passed and called later — the basis of callbacks and dispatch tables.

qsort from <stdlib.h> takes a comparison function pointer, making it work for any type.

Read complex declarations with the clockwise/spiral rule: int (*fp)(int, int) is a pointer to a function taking two ints and returning int.

Code (C17)

#include <stdio.h>
#include <stdlib.h>

int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }

int cmp_desc(const void *a, const void *b) {
    return *(const int *)b - *(const int *)a;
}

int main(void) {
    int (*ops[])(int, int) = {add, mul};
    printf("%d %d\n", ops[0](3, 4), ops[1](3, 4));  // 7 12

    int v[] = {4, 9, 1, 7};
    qsort(v, 4, sizeof v[0], cmp_desc);
    for (int i = 0; i < 4; i++) printf("%d ", v[i]);
    return 0;
}

Remember

  • Function name decays to its address.
  • qsort comparator returns <0, 0, >0.
  • Use typedef to simplify pointer types.

Interview questions

What are function pointers used for?

Callbacks (qsort, event handlers), dispatch tables, state machines and plugin-style interfaces.

Array of pointers vs pointer to array?

int *a[5] is 5 pointers to int; int (*a)[5] is one pointer to an array of 5 ints.

Practise C with the AI mentor

Lesson test

Take an 8-question test on “Function Pointers & Callbacks” — concepts, output prediction, bug spotting and interview questions.

Can't find a C topic you need for exams or placements? Request it and we'll add it.