bsearch_s

From RAD Studio
Jump to: navigation, search

Go Up to stdlib.h Index


Header File

stdlib.h

Category

Searching and sorting utilities

Prototype

void *bsearch_s(const void * __key, const void * __base,
                rsize_t __nelem, rsize_t __width,
                (_USERENTRY *__fcmp)(const void *k, const void *i, void *__context),
                void *__context);

Description

Replaces bsearch adding security enhancements.

bsearch_s searches a table (array) of __nelem elements in memory and returns the address of the first entry in the table that matches the search key defined by __base.

The size of each element in the array is specified by __width.

The comparison function _fcmp must be used with the _USERENTRY calling convention. The array __fcmp is called on must be sorted in ascending order.

__fcmp is called with three arguments: k(the key element), y(an element in the array), and __context(that is passed directly to the __fcmp function in order to allow a more generic user implementation). __fcmp returns an integer that takes its values as follows:

  • < 0 if *k < *y
  • == 0 if *k == *y
  • > 0 if *k > *y

Return Value

bsearch_s returns the address of the first element in the array that matches the search key. If no match is found, then bsearch_s returns null.

Example

#include <stdlib.h>
#include <stdio.h>
typedef int (*fptr)(const void*, const void*, void*);
#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
int numarray[] = {123, 145, 512, 627, 800, 933};
int numeric (const int *p1, const int *p2)
{
  return(*p1 - *p2);
}
#pragma argsused
int lookup(int key)
{
  int  *itemptr;
  /* The cast of (int(*)(const void *,const void*))
      is needed to avoid a type mismatch error at
      compile time */
  itemptr = (int *) bsearch_s(&key, numarray, NELEMS(numarray),
      sizeof(int), (fptr)numeric, NULL);
  return (itemptr != NULL);
}
int main(void)
{
  if (lookup(512))
      printf("512 is in the table.\n");
  else
      printf("512 isn't in the table.\n");
  return 0;
}

Portability

POSIX Win32 ANSI C ANSI C++

+

+

+

+

See Also