Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is bsearch_s() in C?

Khizar Hayat Saani

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);

Parameters

Let’s take a deeper look into the input parameters of the function.

  • key: Pointer to the element being found.
  • arr: Pointer to the array being searched.
  • count: Total number of elements in the array.
  • size: Size, in bytes, of each element in the array.
  • comp: Pointer to the comparison function.
  • context: Additional information to serve as context for comp.

Return

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.

The comparison function

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

Code

#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);
   else
      printf( "\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.

RELATED TAGS

c

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring