www.delorie.com/djgpp/doc/libc/libc_79.html   search  
libc.a reference

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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.

Portability

ANSI/ISO C C89; C99
POSIX 1003.2-1992; 1003.1-2001

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);
...


  webmaster   donations   bookstore     delorie software   privacy  
  Copyright 2004   by DJ Delorie     Updated Apr 2004