student@ubuntu:~$
c 5/5 50 XP

Function Pointers

0%

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 parenthesesint (*fp)(int) vs int *fp(int) are completely different. The parentheses around *fp are mandatory.
  • Wrong comparator signatureqsort expects int (*)(const void *, const void *). Wrong signature = undefined behavior, no warning.
  • Integer overflow in comparatorsreturn a - b overflows. Use explicit if statements.
  • Calling without ()fp is 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).

Unlocks

Complete this skill to see what it unlocks.