Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

bsearch — C23 generic search function

`bsearch(key, base, nmemb, size, compar)` searches `nmemb` objects of `size` bytes and returns a pointer to an element matching `key`, or null. The comparator receives the key first and an array element second, returning a negative value, zero, or a positive value.

Version: C23

Syntax

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

bsearch(key, base, nmemb, size, compar) searches nmemb objects of size bytes and returns a pointer to an element matching key, or null. The comparator receives the key first and an array element second, returning a negative value, zero, or a positive value.

In practice, use it to locate a record in an array ordered by the same comparator. The example searches {2,4,6,8,10} for 8, genuinely dereferences the found element, and separately confirms that 7 is absent.

The array must be partitioned relative to the key into less-than, equal, and greater-than elements in that order; full sorting is the usual way to satisfy this. With duplicates the selected match is unspecified, and an inconsistent comparator violates the contract. C23 preserves the const qualification of base in the result; suppressing the macro to reach the old external declaration is obsolescent. When nmemb is zero, the comparator is not called and no element is found, but every pointer argument must still be valid; an invalid pointer has undefined behavior.

Examples

#include <stdio.h>
#include <stdlib.h>

static int compare_key_to_element(const void *key_pointer, const void *element_pointer) {
    int key = *(const int *)key_pointer;
    int element = *(const int *)element_pointer;
    return (key > element) - (key < element);
}

int main(void) {
    int values[] = {2, 4, 6, 8, 10};
    int wanted = 8;
    int absent = 7;
    int *found = bsearch(&wanted, values, 5, sizeof values[0], compare_key_to_element);
    int *missing = bsearch(&absent, values, 5, sizeof values[0], compare_key_to_element);
    printf("%d %d\n", found == NULL ? -1 : *found, missing == NULL);
    return 0;
}

Result

8 1

In practice, use it to locate a record in an array ordered by the same comparator. The example searches `{2,4,6,8,10}` for `8`, genuinely dereferences the found element, and separately confirms that `7` is absent.

Sources