约 1250 字

约 6 分钟

#C 语言标准库函数 bsearch

#include <stdlib.h>

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

说明

在已排序的数组中用二分搜索查找与 key 等价的元素。

数组须按与本次比较相容的顺序排列。比较回调收到的第一个参数是查找键。C23 的类型通用调用保留被查找数组的 const 限定,上述原型是普通函数版本。

自 C89 起提供。

参数

  • key - 指向要查找的对象。
  • base - 元素连续存储的数组起始地址。
  • nmemb - 数组元素数。
  • size - 每个元素的字节数。
  • compar - 比较回调,按第一个对象小于、等于或大于第二个对象返回负数、零或正数。

返回值

  • 找到时返回元素地址,重复元素中选哪一个由实现决定。找不到时返回空指针。

#示例

#include <stdlib.h>

static int compare_ints(const void *a, const void *b)
{
    int first = *(const int *)a;
    int second = *(const int *)b;
    return (first > second) - (first < second);
}

int main(void)
{
    const int values[] = {1, 3, 7, 9};
    int key = 7;
    const int *found = bsearch(&key, values, 4, sizeof values[0], compare_ints);
    return found == NULL || *found != key;
}

#相关接口

#参考标准

更新: 2026/11/28

作者: planc

创建: 2026/11/28