lfind
void*  lfind ( const void * key, const void * base, size_t num, size_t width, int (*fncomparison)(const void *, const void * ) );
stdlib.h
  cplusplus.com  

Linear search.
  Searches the given key in an array pointed by base and formed by num elements, each of a size of width bytes, and returns the address of the first entry in the table that matches the serach key. The comparison is performed by function fncomparison that is called back one or more times during the search.
  This function performs a linear search, so the array does not need to be sorted before calling it.

Parameters.

key
Pointer to the object that serves as key for the search.
base
Pointer to the base of the array where the search is performed.
num
Number of elements in the array pointed by base.
width
Width of each element in the array.
fncompare
Function that compares two elements. This should be provided by the caller to this function and must follow or be casted to a declaration like:
int fncompare (const void * elem1, const void * elem2 );
The function should receive two parameters (elem1 and elem2) that are pointers to elements, and should return an int value being 0 if both parameters are equal or any other value if they are different.

Return Value.
  A pointer to an entry in the array that matches the search key.
  If key is not found, a NULL pointer is returned.

Portability.
  Not defined in ANSI-C. Supported by many compilers.

Example.

/* lfind example */
#include <stdio.h>
#include <stdlib.h>

int values[] = { 10, 40, 100, 20, 90, 25};

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

main ()
{
  int * pItem;
  int key = 40;
  pItem = (int*) lfind (&key, values, 6, sizeof (int), compare);
  if (pItem!=NULL)
    printf ("%d is in the array",*pItem);
  else
    printf ("%d is not in the array",key);
  return 0;
}
In the example there is an array of unsorted int values. There is also a function called compare that subtracts the values pointed by the two parameters as if they were pointers to int values (that indeed they are), so it returns 0 if they are equal and any other value if not. In the main function there is a call to lfind with 40 as key, so the function will find that key in the values array and the program will print out:
40 is in the array

See also.
  bsearch, qsort


© The C++ Resources Network, 2000