1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Advanced Pointers

By , About.com Guide

7 of 8

Other Uses of a Function Pointer

Other Uses of Function Pointers

This can requires a slight shift in your thinking especially if you are new to pointers. If you are writing library routines and want to provide the caller of your routines with some kind of status then you need to implement a callback routine. When you call the library routine, you provide the callback function name and during processing the library routine will call your status function a number of times.
  • Always check a function pointer has been assigned before calling it.
Some libraries like qsort in <stdlib.h> requires that you provide or even implement a comparison routine. You don't need to implement one for sorting strings because qsort can use strcmp() for string comparisons.

This is the declaration for qsort.

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) ;
The declaration for strcmp below matches qsort's requirements.
int strcmp(const char *str1, const char *str2) ;
Example 3 on page 8 shows qsort working with a function we provide to sort ints. The great thing about qsort is that it sorts anything, as long as you provide it with a means to compare two objects. This comparison function must match this definition
int function (const void *,const void *)
This should return 0 if the objects match, -1 if the left one is less than the right one and 1 if the right one is less than the left one. In example 3, comp does this. Remember that void * means a pointer to anything. It can be a char *, int, struct whatever.

On the next page : Example 3 - Using qsort to sort Ints

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Other Uses of a Function Pointer

©2009 About.com, a part of The New York Times Company.

All rights reserved.