Go to the first, previous, next, last section, table of contents.


Defining the Comparison Function

In order to use the sorted array library functions, you have to describe how to compare the elements of the array.

To do this, you supply a comparison function to compare two elements of the array. The library will call this function, passing as arguments pointers to two array elements to be compared. Your comparison function should return a value the way strcmp (see section String/Array Comparison) does: negative if the first argument is "less" than the second, zero if they are "equal", and positive if the first argument is "greater".

Here is an example of a comparison function which works with an array of numbers of type double:

int
compare_doubles (const double *a, const double *b)
{
  return (int) (*a - *b);
}

The header file `stdlib.h' defines a name for the data type of comparison functions. This type is a GNU extension.

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


Go to the first, previous, next, last section, table of contents.