Skip to content
Justice Tech School

Function Pointers and Callbacks

A function pointer stores the address of a function. Pass one to qsort or write your own callback API.

Example
#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 apply(int (*f)(int, int), int x, int y) { return f(x, y); }
int cmp(const void *a, const void *b) { return *(const int *)a - *(const int *)b; }
int main(void) {
    printf("%d %d\n", apply(add, 3, 4), apply(mul, 3, 4));
    int v[] = {5, 2, 9, 1};
    qsort(v, 4, sizeof(int), cmp);
    for (int i = 0; i < 4; i++) printf("%d ", v[i]);
    printf("\n");
    return 0;
}

Result

7 12
1 2 5 9 

Exercise

Pointer to int function.

int (*f)int)

Quiz Test

What does qsort need?

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