目录

void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))

描述 (Description)

C库函数void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))函数搜索nitems对象的数组,初始成员对于与key指向的对象匹配的成员,由base指向。 数组的每个成员的sizesize指定。

根据compar引用的比较函数,数组的内容应按升序排序。

声明 (Declaration)

以下是bsearch()函数的声明。

void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))

参数 (Parameters)

  • key - 这是指向作为搜索关键字的对象的指针,类型为void *。

  • base - 这是指向执行搜索的数组的第一个对象的指针,类型转换为void *。

  • nitems - 这是base指向的数组中的元素数。

  • size - 这是数组中每个元素的大小(以字节为单位)。

  • compare - 这是比较两个元素的函数。

返回值 (Return Value)

此函数返回指向数组中与搜索键匹配的条目的指针。 如果未找到key,则返回NULL指针。

例子 (Example)

以下示例显示了bsearch()函数的用法。

#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void * a, const void * 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\n", *item);
   } else {
      printf("Item = %d could not be found\n", *item);
   }
   return(0);
}

让我们编译并运行上面的程序,它将产生以下结果 -

Found item = 32
↑回到顶部↑
WIKI教程 @2018