bsearch
From cppreference.com
Defined in header <stdlib.h>
|
||
Finds an element equal to element pointed to by key
in an array pointed to by ptr
. The array contains count
elements of size size
. Function pointed to by comp
is used for object comparison.
Contents |
[edit] Parameters
key | - | pointer to the element to search for | |||||||||
ptr | - | pointer to the array to examine | |||||||||
count | - | number of element in the array | |||||||||
size | - | size of each element in the array in bytes | |||||||||
comp | - | comparison function which returns a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equal.
The function must not modify the objects passed to it. |
[edit] Return value
pointer to the found element or NULL otherwise.
[edit] Example
#include <stdlib.h> #include <stdio.h> struct data { int nr; char const *value; } dat[] = { {1, "Foo"}, {2, "Bar"}, {3, "Hello"}, {4, "World"} }; int data_cmp(void const *lhs, void const *rhs) { struct data const *const l = lhs; struct data const *const r = rhs; return l->nr < r->nr; } int main(void) { struct data key = { .nr = 3 }; struct data const *res = bsearch(&key, dat, sizeof(dat)/sizeof(dat[0]), sizeof(dat[0]), data_cmp); if(!res) { printf("No %d not found\n", key.nr); } else { printf("No %d: %s\n", res->nr, res->value); } }
Output:
No 3: Hello
[edit] See also
sorts a range of elements with unspecified type (function) |
|