Function Pointers
Challenge Gallery
Quick Reference
Declaration syntax:
int (*fp)(int, int); // fp is a pointer to function(int,int)->int
typedef int (*MathOp)(int, int); // MathOp is an alias for the above
Using function pointers:
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int (*op)(int, int) = add; // Point to add
printf("%d\n", op(3, 5)); // Calls add(3, 5) → 8
op = sub; // Repoint to sub
printf("%d\n", op(3, 5)); // Calls sub(3, 5) → -2
The generic sort pattern:
typedef int (*Comparator)(const Student *, const Student *);
void sort_roster(Student roster[], int size, Comparator cmp) {
// ... selection sort using cmp(&roster[j], &roster[min]) < 0 ...
}
// Caller picks the comparison:
sort_roster(roster, n, compare_by_name);
sort_roster(roster, n, compare_by_gpa);
qsort (standard library):
#include <stdlib.h>
qsort(array, count, sizeof(element), comparator_function);
Common Pitfalls
- Missing parentheses —
int (*fp)(int)vsint *fp(int)are completely different. The parentheses around*fpare mandatory. - Wrong comparator signature —
qsortexpectsint (*)(const void *, const void *). Wrong signature = undefined behavior, no warning. - Integer overflow in comparators —
return a - boverflows. Use explicit if statements. - Calling without () —
fpis the address.fp()calls the function. Forgetting()passes the address instead of calling. - Type mismatch — A function pointer must match the target function’s signature exactly (return type + parameter types).