Home > Programming > Functions using the "C" programming language > example33.c |
/*
In this example we demonstrate how to use a function pointer as a
parameter
to a function. We use the library function qsort.
Note: The function pointer argument is a pointer to a user-supplied
function
that compares two elements and returns a value specifying their
relationship.
*/
#include <stdio.h>
#include <stdlib.h>
/*
User-suplied function.
The user-suplied function must return an integer value that is
<0 if first element is less than second element
=0 if the two elements are equivalent
>0 if first element is greater than second element
*/
int sort_function( const void *a, const void
*b)
{
return *(int
*)(a)-*(int *)(b);
}
int int_list[5] = { 1, 5, 4, 2, 3 };
void main(void)
{
int x;
/*
Print numbers before sorting
*/
printf("Before sorting ...\n");
for (x = 0; x < 5; x++)
printf("%d\n", int_list[x]);
qsort((void *)int_list, 5, sizeof(int_list[0]), sort_function);
/*
Print numbers after sorting
*/
printf("After sorting ...\n");
for (x = 0; x < 5; x++)
printf("%d\n", int_list[x]);
}
© 2004 Jim Valavanis