Modular C · 9 min read · Intermediate
Function Pointers & Callbacks (qsort)
Pass functions as arguments in C to build flexible callbacks and sort any array type using stdlib's qsort().
What you'll learn
- Declare and invoke a function pointer cleanly with typedef
- Pass a custom comparator callback to qsort()
- Understand how void * enables generic algorithms in C
In C, functions live at memory addresses just like data. Passing a function pointer lets libraries like qsort() sort arrays of any type (int, double, struct) by delegating comparisons to your callback function.
Fill-in-the-Blank Exercise
Call stdlib qsort
Sort an array of 4 ints using the cmp_asc callback function.
(nums, 4, sizeof(int), );Live Code Lab
Cqsort_demo.c
Expected OutputClick “Run Live” to compile with GCC 13 (C11)
65 74 88 91
Check Your Understanding
Score: 0 / 1
1. Why does qsort's comparator take const void * parameters?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.