What are function pointers?
Why do we need them?
This is a discussion on Function pointers within the C Programming forums, part of the General Programming Boards category; What are function pointers? Why do we need them?...
What are function pointers?
Why do we need them?
Hope is the first step on the road to disappointment.
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;
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.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));
As an example of usage, here are two applications for different types of arguments;
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.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]); }