Microchip Technology XC8 Standard Compiler (Workstation) SW006021-1 SW006021-1 User Manual
Product codes
SW006021-1
MPLAB
®
XC8 C Compiler User’s Guide
DS52053B-page 324
2012 Microchip Technology Inc.
BSEARCH
Synopsis
#include <stdlib.h>
void * bsearch (const void * key, void * base, size_t n_memb,
size_t size, int (*compar)(const void *, const void *))
Description
The
bsearch()
function searches a sorted array for an element matching a particular
key. It uses a binary search algorithm, calling the function pointed to by
compar
to
compare elements in the array.
Example
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct value {
char name[40];
int value;
} values[100];
int
val_cmp (const void * p1, const void * p2)
{
return strcmp(((const struct value *)p1)->name,
((const struct value *)p2)->name);
}
void
main (void)
{
char inbuf[80];
int i;
struct value * vp;
i = 0;
while(gets(inbuf)) {
sscanf(inbuf,”%s %d”, values[i].name, &values[i].value);
i++;
}
qsort(values, i, sizeof values[0], val_cmp);
vp = bsearch(“fred”, values, i, sizeof values[0], val_cmp);
if(!vp)
printf(“Item ’fred’ was not found\n”);
else
printf(“Item ’fred’ has value %d\n”, vp->value);
}
See Also
qsort()
Return Value
A pointer to the matched array element (if there is more than one matching element,
any of these may be returned). If no match is found, a null is returned.
any of these may be returned). If no match is found, a null is returned.
Note
The comparison function must have the correct prototype.