Explain Pointers to a Function with example

Explain Pointers to a Function with example

  Pointer to a function are perhaps on of the more confusing uses of pointers in C. Pointers to functions are not as common as other pointer uses. However, one common use is in a passing pointers to a function as a parameter in a function call. (Yes this is getting confusing, hold on to your hats for a moment).

This is especially useful when alternative functions maybe used to perform similar tasks on data. You can pass the data and the function to be used to some control function for instance. As we will see shortly the C standard library provided some basic sorting ( qsort) and searching (bsearch) functions for free. You can easily embed your own functions.

To declare a pointer to a function do:

int (*pf) ();

This simply declares a pointer *pf to function that returns and int. No actual function is pointed to yet.

If we have a function int f() then we may simply (!!) write:

pf = &f;

For compiler prototyping to fully work it is better to have full function prototypes for the function and the pointer to a function:

int f(int);

int (*pf) (int) = &f;

Now f() returns an int and takes one int as a parameter.

You can do things like:

ans = f(5);

ans = pf(5);

which are equivalent.

The qsort standard library function is very useful function that is designed to sort an array by a key value of any type into ascending order, as long as the elements of the array are of fixed type.

qsort is prototyped in (stdlib.h):

void qsort(void *base, size_t num_elements, size_t element_size,

   int (*compare)(void const *, void  const *));

The argument base points to the array to be sorted, num_elements indicates how long the array is, element_size is the size in bytes of each array element and the final argument compare is a pointer to a function.

qsort calls the compare function which is user defined to compare the data when sorting. Note that qsort maintains it's data type independence by giving the comparison responsibility to the user. The compare function must return certain (integer) values according to the comparison result:

less than zero

: if first value is less than the second value

zero

: if first value is equal to the second value

greater than zero

: if first value is greater than the second value

Some quite complicated data structures can be sorted in this manner. For example, to sort the following structure by integer key:

typedef struct {

        int   key;

                                                             struct other_data;

} Record;

We can write a compare function, record_compare:

int record\_compare(void const *a, void  const *a)

  {  return ( ((Record *)a)->key - ((Record *)b)->key );

  }

Assuming that we have an array of array_length Records suitably filled with date we can call qsort like this:

qsort( array, arraylength, sizeof(Record), record_compare);


Labels: