Latest web development tutorials

C library functions - bsearch ()

C standard library - <stdlib.h> C standard library - <stdlib.h>

description

C library functionsvoid * bsearch (const void * key , const void * base, size_t nitems, size_t size, int (* compar) (const void *, const void *)) of nitemsarray of objects to perform binarysearch,base point to be Find anarray,key point to find theelements,size specifies the size of each element in the array.

Contents of the array should be based on the corresponding comparison functioncompar in ascending order.

statement

Here is () statement bsearch function.

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

parameter

  • key - pointer to find the element type to void *.
  • base - point to carry out an array of pointers to find the first object type to void *.
  • nitems - pointed to the number of base elements in the array.
  • size - the size of each element in the array, in bytes.
  • compar - function used to compare two elements.

return value

If the search is successful, the function returns a pointer to a pointer to an array of matching elements, otherwise it returns a null pointer. .

Examples

The following example demonstrates bsearch () function is used.

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


int cmpfunc(const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int values[] = { 5, 20, 29, 32, 63 };

int main ()
{
   int *item;
   int key = 32;

   /* 使用 bsearch() 在数组中查找值 32 */
   item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
   if( item != NULL ) 
   {
      printf("Found item = %d\n", *item);
   }
   else 
   {
      printf("Item = %d could not be found\n", *item);
   }
   
   return(0);
}

Let's compile and run the above program, which will result in the following:

Found item = 32

C standard library - <stdlib.h> C standard library - <stdlib.h>