The classic example is sorting an array of elements using the qsort function. Its last argument is a function pointer to the routine that compares two elements, passed as void pointers.
void qsort(void *base,
size_t nmemb,
size_t size,
int(*compar)(const void *, const void *));
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:
struct president {
char * fname;
char * lname;
unsigned int number;
};
If you wanted to sort an array of them by their "number" field you could implement a "compar" (comparator) function as follows:
int compare_presidents(const void * v1, const void * v2) {
struct president p1 = * ((struct president *) v1);
struct president p2 = * ((struct president *) v2);
return (p1.number - p2.number); // Compare by number ascending.
}
And you could sort an array of such structures as such:
qsort(presidents, num_presidents, sizeof(struct president), compare_presidents);
qsort()is an example of where function pointers are used. This allows the same sorting algorithm based on different criteria (and types).sqrt??qsort.qsortwithsqrt.sqrtis Square Root function.