I feel like I have a pretty good handle on pointers in C. Mostly, I use
them to pass arrays to functions.
But I’ve noticed in looking at many different code examples that it’ not uncommon to
see pointers to functions. It’s not at all clear to me why this would be useful?
Are there some classic instances where the pointer to function model is handy or essential to implement?
The classic example is sorting an array of elements using the
qsortfunction. Its last argument is a function pointer to the routine that compares two elements, passed as void pointers.Using a function pointer here is essential since the sorting routine can’t be made generic enough to know how you want to compare the elements, so the function pointer is essentially a “callback” that the sort function uses to let you extend it.
[Edit] For example, suppose you had the following structure defined:
If you wanted to sort an array of them by their “number” field you could implement a “compar” (comparator) function as follows:
And you could sort an array of such structures as such: