bsearch_s
is a built-in function defined in the <stdlib.h>
header. It is available for use from the C11 version of C.
To use the function, we must define __STDC_LIB_EXT1__
and set __STDC_WANT_LIB_EXT1__
to 1
.
Below is the function prototype:
void* bsearch_s (const void *key, const void *arr, rsize_t count, rsize_t size, int (*comp)(const void *, const void *, void *), void *context);
Let’s take a deeper look into the input parameters of the function.
The
bsearch_s
function returns a pointer to the key element.
If the key element is not found or dealt with a runtime error, a null pointer is returned.
Below the prototype for the comp function:
int cmp(const void *key, const void *element, void* context);
The first argument is the key that we find, while the second argument may be any element from the array.
The comp function returns:
-1
if the key is less than the element
0
if the key is equal to the element
1
if the key is greater than the element
#define __STDC_WANT_LIB_EXT1__ 1#include <stdlib.h>#include <stdio.h>int comp(void const *lhs, void const *rhs, void* context){const int* l = (const int*) lhs;const int* r = (const int*)rhs;if (*l < *r) return -1;else if (*l > *r) return 1;else return 0;}int main(){int arr[] = {0, 2, 4, 6, 8, 10};int key = 4;int* result = bsearch_s(&key, arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), comp, NULL);if(result)printf("\n%d found\n", *result);elseprintf( "\nNot found!\n" );}
Here we’re dealing with a simple integer
array; hence, there is no need for context and we can pass NULL
in its place.
Note that the array we are searching is sorted. This is a pre-requisite for
binary search
.
Free Resources