Understanding Pointers to Functions in C
This article explains
Pointers to Functions in C. It is a copy of the article written by Ted Jensen. I
have basically cut short his article and republished it on this site.
There may be thousands of programmers who know how to use pointers to
functions, but I know that there are many..many more who have no idea what it is
and how to use it. This article is for those who know C programming very well,
but are not yet familiar with this wonderful concept of using pointers to
functions. This is definitely not an article for beginners. Believe me once you
learn this you would find numerous uses of this in professional
projects.
My aim to is to explain
pointers to functions with the a program that should be capable of sorting
virtually any collection of data that can be stored in an array. This might be
an array of strings, integers, floats, or even structures. The sorting algorithm
can be the same for all. For example, it could be a simple bubble sort
algorithm, or the more complex quick-sort algorithm. I'll use a simple bubble
sort algorithm for demonstration purposes.
Note :
Remember to add the necessary header files and other minor details. I have only
presented the important part of the code. The unsorted and sorted collection is
not printed to the terminal. You have to add code on your own for
that.
Program 1
We could write a simple program as
shown below. If we call that function bubble(), a sort program shown
below
If you print the contents of the array before and after the call to bubble() then you would notice that the elements are sorted.
One thing that I would like to state bluntly is that in case you haven't understood what is happening in the above program, then you do not fit the target audience for this article. Bubble sorting is one of the simplest sorting algorithms available and you should be knowing that. For the rest who have figured out what is happening.. Do enjoy the rest of the article..
Here our function is designed to sort an array of integers. What we want to do now is see if we can convert this code so we can use any data type, i.e. not be restricted to integers. At the same time we don't want to have to analyze our algorithm and the code associated with it each time we use it.
Program 2
We start by removing the comparison from within the function bubble() so as to make it relatively easy to modify the comparison function without having to rewrite portions related the actual algorithm.
Select All Code
|
|
If our goal is to make our sort routine data type independent, one way of doing this is to use pointers to type void to point to the data instead of using the integer data type. As a start in that direction let's modify a few things in the above so that pointers can be used.
Program 3
To begin with, we'll stick with pointers to type integer.
Select All Code
|
|
Note the changes. We are now passing a pointer to an integer (or array of integers) to bubble(). And from within bubble we are passing pointers to the elements of the array that we want to compare to our comparison function. And, of course we are dereferencing these pointer in our compare() function in order to make the actual comparison.
Program 4
Our next step will be to convert the pointers in bubble() to pointers to type void so that that function will become more type insensitive. This is shown below
Select All Code
|
|
Note that, in doing this, in compare() we had to introduce the casting of the void pointer types passed to the actual type being sorted. But, as we'll see later that's okay. And since what is being passed to bubble() is still a pointer to an array of integers, we had to cast these pointers to void pointers when we passed them as parameters in our call to compare()
We now address the problem of what we pass to bubble(). We want to make the first parameter of that function a void pointer also. But, that means that within bubble() we need to do something about the variable t, which is currently an integer. Also, where we use t = p[j-1]; the type of p[j-1] needs to be known in order to know how many bytes to copy to the variable t (or whatever we replace t with).
Currently, in Program 4, knowledge within buffer() as to the type of the data being sorted (and hence the size of each individual element) is obtained from the fact that the first parameter is a pointer to type integer. If we are going to be able to use bubble() to sort any type of data, we need to make that pointer a pointer to type void. But, in doing so we are going to lose information concerning the size of individual elements within the array. So, in Program 5 we will add a separate parameter to handle this size information.
Program 5
These changes, from Program 4 to Program 5 are, perhaps, a bit more extensive than those we have made in the past. So, compare the two modules carefully for differences.
Select All Code
|
|
Note that I have changed the data type of the array from int to long to illustrate the changes needed in the compare() function. Within bubble I've done away with the variable t (which we would have had to change from type int to type long). I have added a buffer of size 4 unsigned characters, which is the size needed to hold a long (this will change again in future modifications to this code). The unsigned character pointer *bp is used to point to the base of the array to be sorted, i.e. to the first element of that array.
We also had to modify what we passed to compare(), and how we do the swapping of elements that the comparison indicates need swapping. Use of memcpy() and pointer notation instead of array notation work towards this reduction in type sensitivity.
Again, making a careful comparison of Program 5 with Program 4 can result in improved understanding of what is happening and why.
Program 6
We move now to Program 6 where we use the same function bubble() that we used in Program 5 to sort strings instead of long integers. Of course we have to change the comparison function since the means by which strings are compared is different from that by which long integers are compared. And,in Program 6 we have deleted the lines within bubble() that were commented out in Program 5.
Select All Code
|
|
But, the fact that bubble() was unchanged from that used in Program 5 indicates that that function is capable of sorting a wide variety of data types. What is left to do is to pass to bubble() the name of the comparison function we want to use so that it can be truly universal.
Program 7
Just as the name of an array is the address of the first element of the array in the data segment, the name of a function decays into the address of that function in the code segment. Thus we need to use a pointer to a function. In this case the comparison function. Pointers to functions must match the functions pointed to in the number and types of the parameters and the type of the return value.
In our case, we declare our function pointer as:
int (*fptr)(const void *p1, const void *p2);
Note that were we to write:
int *fptr(const void *p1, const void *p2);
We would have a function prototype for a function which returned a pointer to type int. That is because in C the parenthesis () operator have a higher precedence than the pointer * operator. By putting the parenthesis around the string (*fptr) we indicate that we are declaring a function pointer. We now modify our declaration of bubble() by adding, as its 4th parameter, a function pointer of the proper type. It's function prototype becomes:
void bubble(void *p, int width, int N,
int(*fptr)(const void *, const void *));
When we call the bubble(), we insert the name of the comparison function that we want to use. Program 7 illustrate how this approach permits the use of the same bubble() function for sorting different types of data.
Select All Code
|
|
That's it. I guess you must have understood how to use pointers to functions. I am sure that now onwards you would definitely try to think of incorporating this in your programs so that it becomes more scalable. You can always use pointers to functions to improve the design of your programs. But to master this skill requires experience. So give it a try and you will get the hang of it.
All comments and feedback may be sent to paikiran @ yahoo.com
|
|