A function pointer is a pointer that, when dereferenced, calls a function.
We need them for many reasons. One is to allow actions to be applied to some data.
Consider the humble qsort() function, which is declared in stdlib.h with a prototype which looks like;
Code:
void qsort(void *array_to_sort, size_t number_of_elements, size_t size_of_an_element, width, int (*comparer_function)(const void *first, const void *second));
The comparer_function is a pointer to a function that takes two void arguments, and return a value indicating the relationship between *first and *second. Specifically, the function is required to return a negative integer if *first < *second, zero if they are equal, and a positive integer if *first > * second.
As an example of usage, here are two applications for different types of arguments;
Code:
/* untested code follows; intended to show idea */
#include <string.h>
#include <stdio.h>
int double_comparer(const void *first, const void *second)
{
double f = *((double *)first);
double s = *((double *)second);
if (f < s)
return -1;
else if (f > s)
return 1;
else
return 0;
}
int string_comparer(const void *first, const void *second)
{
return strcmp((const char *)first, (const char *)second);
}
int main()
{
double x[] = {1.0, -1.0, 6.0, 3.0};
char *s[3];
s[0] = "BA";
s[1] = "CD";
s[2] = "AB";
qsort(x, 4, sizeof(double), double_comparer);
/* x will now be sorted. Print to see*/
printf("%f %f %f %f\n", x[0], x[1], x[2], x[3]);
qsort(s, 3, sizeof (char *), string_comparer);
/* s will now be sorted. Print to see*/
printf("%s %s %s\n", s[0], s[1], s[2]);
}
The point is that qsort does not need to know how to manipulate the data it receives. The only information it needs is the address where the data, the size of each element, number of elements, and a pointer to a function that can be used to compare elements.