Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- libc - <b>bsearch</b> http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
bsearch
=======

Syntax
------

     #include <stdlib.h>
     
     void *bsearch (const void *key, const void *base, size_t num,
       size_t size, int (*ptf)(const void *ckey, const void *celem));

Description
-----------

Given an array of values, perform a binary search on the values looking
for value that "matches" the given key.  A match is determined by
calling the provided function PTF and passing it the key as CKEY and a
pointer to one of the elements of the array as CELEM.  This function
must return a negative number if the key is closer than the element to
the beginning of the array, positive if it is closer to the end, and
zero if the element matches the key.

The array begins at address BASE and contains NUM elements, each of
size SIZE.

Return Value
------------

Returns a pointer to the element that matches the key, else NULL.

Example
-------

     typedef struct {
       int a, b;
     } q;
     
     int compare(void *key, void *elem)
     {
       return *(int *)key - ((q *)elem)->a;
     }
     
     q qlist[100];
     
     ...
     q *match = bsearch(4, qlist, 100, sizeof(q), compare);
     printf("4->%d=n", match->b);
     ...


Online resources provided by: http://www.X-Hacker.org --- NG 2 HTML conversion by Dave Pearson