bsearch函数用法详解
bsearch函数简介
- 头文件包含
#include <stdlib.h>
- 函数定义
void *bsearch(const void * key , const void * base ,
size_t nmemb , size_t size ,
int (* compar )(const void *, const void *));
bsearch函数常见使用错误
- 编译错误
warning: implicit declaration of function ‘bsearch’ [-Wimplicit-function-declaration]
解决办法:包含头文件
#include <stdlib.h>
bsearch函数详细描述
bsearch ()函数搜索一个由nmemb对象组成的数组,该数组的初始成员由base 指向,以查找与key 指向的对象匹配的成员。数组每个成员的大小由size 指定
数组的内容应该根据compar 引用的比较函数按升序排序。compar例程应该有两个参数,它们依次指向key对象和数组成员,如果发现key对象分别小于、匹配或大于数组成员,则应该返回一个小于、等于或大于零的整数。
bsearch函数返回值
bsearch ()函数返回一个指向数组匹配成员的指针,如果没有找到匹配项,则返回NULL。如果有多个元素与键匹配,则返回的元素未指定。
bsearch函数使用举例
下面的示例首先使用qsort (3)对结构数组进行排序,然后使用bsearch ()检索所需的元素
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct mi {
int nr;
char *name;
} months[] = {
{ 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
{ 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
{ 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
};
#define nr_of_months (sizeof(months)/sizeof(months[0]))
static int
compmi(const void *m1, const void *m2)
{
const struct mi *mi1 = m1;
const struct mi *mi2 = m2;
return strcmp(mi1\->name, mi2\->name);
}
int
main(int argc, char **argv)
{
qsort(months, nr_of_months, sizeof(months[0]), compmi);
for (int i = 1; i < argc; i++) {
struct mi key;
struct mi *res;
key.name = argv[i];
res = bsearch(&key, months, nr_of_months,
sizeof(months[0]), compmi);
if (res == NULL)
printf("\(aq%s\(aq: unknown month\en", argv[i]);
else
printf("%s: month #%d\en", res\->name, res\->nr);
}
exit(EXIT_SUCCESS);
}
评论区