bsearch() – C语言库函数
C库函数 void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) 函数搜索一个数组的 nitems 对象,初始成员其中所指向的基础,相匹配的key指向的对象的成员。指定尺寸的阵列中的每个成员的大小。
该数组的内容应该是按升序排序的顺序,根据通过比较参考的比较函数。
声明
以下是 bsearch() 函数的声明。
void*bsearch(constvoid*key,constvoid*base,size_t nitems,size_t size,int(*compar)(constvoid*,constvoid*))
参数
-
key -- 这是作为搜索的关键对象的指针,铸成一个void *类型。
-
base -- 这是在执行搜索的数组的第一个对象的指针,铸成一个void *类型。
-
nitems -- 这是由基部指向的数组中的元素数目。
-
size -- 这是在数组中的每个元素的大小(以字节为单位)。
-
compar -- 这个函数比较两个元素。
返回值
这个函数返回一个指针数组中的一个条目匹配的搜索键。如果没有找到钥匙,返回一个NULL指针。
例子
下面的例子演示了如何使用 bsearch() 函数。
#include<stdio.h>#include<stdlib.h>int cmpfunc(constvoid* a,constvoid* b){return(*(int*)a -*(int*)b );}int values[]={5,20,29,32,63};int main (){int*item;int key =32;/* using bsearch() to find value 32 in the array */ item =(int*) bsearch (&key, values,5,sizeof(int), cmpfunc);if( item != NULL ){ printf("Found item = %d ",*item);}else{ printf("Item = %d could not be found ",*item);}return(0);}
让我们编译和运行上面的程序,这将产生以下结果:
Found item = 32