B

Top  Previous  Next

bsearch

#include <stdlib.h>

void *bsearch (

   const void *key,

   const void *base,

   size_t      nmemb,

   size_t      size,

   int       (*compar) (const void *, const void *)

);

 stand-alone

 

This function searches an array of objects for an element matching a given key. The result of bsearch is a pointer to the array element located by the search; if no match is found, a null pointer is returned.

 

bsearch is not limited to any particular data type; it is provided with a comparison function which allows it to compare two objects of any arbitrary type used by the program.

 

The array to be searched starts at base and has nmemb elements, each of which is size chars long. key points to the item to be searched for, which must have the same type as the elements of the array being searched.

 

The compar argument points to a comparison function which, given pointers to two objects of the same type as those pointed to by key and base, returns a negative integer to indicate the first is 'less than' the second, a positive integer to indicate that the first object is 'greater than' the second, or 0 to indicate that the two objects are 'equal'.

 

Before calling bsearch, the array must be sorted into ascending order with respect to the comparison function pointed to by compar. This operation can often be most easily performed by the qsort function that can sort an arbitrary array into order. Like bsearch, it uses a comparison function to determine the ordering to be used.