Header File
stdlib.h
Category
Memory and String Manipulation Routines
Prototype
void *bsearch(const void *key, const void *base, size_t nelem, size_t width, int (_USERENTRY *fcmp)(const void *, const void *));
Description
Binary search of an array.
bsearch searches a table (array) of nelem elements in memory, and returns the address of the first entry in the table that matches the search key. The array must be in order. If no match is found, bsearch returns 0.
fcmp is called with two arguments: elem1 and elem2. Each argument points to an item to be compared. The comparison function compares each of the pointed-to items (*elem1 and *elem2), and returns an integer based on the results of the comparison.
bsearch returns the address of the first entry in the table that matches the search key. If no match is found, bsearch returns 0.
Example
#include <stdlib.h> #include <stdio.h> typedef int (*fptr)(const void*, const void*); #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) int numarray[] = {123, 145, 512, 627, 800, 933}; int numeric (const int *p1, const int *p2) { return(*p1 - *p2); } #pragma argsused int lookup(int key) { int *itemptr; /* The cast of (int(*)(const void *,const void*)) is needed to avoid a type mismatch error at compile time */ itemptr = (int *) bsearch (&key, numarray, NELEMS(numarray), sizeof(int), (fptr)numeric); return (itemptr != NULL); } int main(void) { if (lookup(512)) printf("512 is in the table.\n"); else printf("512 isn't in the table.\n"); return 0; }
Portability
POSIX |
Win32 |
ANSI C |
ANSI C++ |
+ |
+ |
+ |
+ |
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
|
What do you think about this topic? Send feedback!
|