home *** CD-ROM | disk | FTP | other *** search
/ PC Extra Super CD 1998 January / PCPLUS131.iso / DJGPP / V2 / DJLSR201.ZIP / src / libc / ansi / stdlib / bsearch.txh < prev    next >
Encoding:
Text File  |  1995-07-10  |  1.2 KB  |  49 lines

  1. @node bsearch, misc
  2. @subheading Syntax
  3.  
  4. @example
  5. #include <stdlib.h>
  6.  
  7. void *bsearch (const void *key, const void *base, size_t num, 
  8.   size_t size, int (*ptf)(const void *ckey, const void *celem));
  9. @end example
  10.  
  11. @subheading Description
  12.  
  13. Given an array of values, perform a binary search on the values looking
  14. for value that "matches" the given key.  A match is determined by
  15. calling the provided function @var{ptf} and passing it the key as
  16. @var{ckey} and a pointer to one of the elements of the array as
  17. @var{celem}.  This function must return a negative number if the key is
  18. closer than the element to the beginning of the array, positive if
  19. it is closer to the end, and zero if the element matches the key.
  20.  
  21. The array begins at address @var{base} and contains @var{num} elements,
  22. each of size @var{size}. 
  23.  
  24. @subheading Return Value
  25.  
  26. Returns a pointer to the element that matches the key, else @var{NULL}.
  27.  
  28. @subheading Example
  29.  
  30. @example
  31. typedef struct @{
  32.   int a, b;
  33. @} q;
  34.  
  35. int compare(void *key, void *elem)
  36. @{
  37.   return *(int *)key - ((q *)elem)->a;
  38. @}
  39.  
  40. q qlist[100];
  41.  
  42. @dots{}
  43. q *match = bsearch(4, qlist, 100, sizeof(q), compare);
  44. printf("4->%d=n", match->b);
  45. @dots{}
  46.  
  47. @end example
  48.  
  49.