Visual Studio 6.0

Performs a linear search for a value; adds to end of list if not found.

void *_lsearch( const void *key, void *base, unsigned int *num, unsigned int width, int (__cdecl *compare)(const void *elem1, const void *elem2) );

Routine Required Header Compatibility
_lsearch <search.h> Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.


LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version

Return Value

If the key is found, _lsearch returns a pointer to the element of the array at base that matches key. If the key is not found, _lsearch returns a pointer to the newly added item at the end of the array.



Object to search for


Pointer to base of array to be searched


Number of elements


Width of each array element


Pointer to comparison routine


Pointer to key for search


Pointer to array element to be compared with key


The _lsearch function performs a linear search for the value key in an array of num elements, each of width bytes in size. Unlike bsearch, _lsearch does not require the array to be sorted. If key is not found, _lsearch adds it to the end of the array and increments num.

The compare argument is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. _lsearch calls the compare routine one or more times during the search, passing pointers to two array elements on each call. compare must compare the elements, then return either nonzero, meaning the elements are different, or 0, meaning the elements are identical.


/* LFIND.C: This program uses _lfind to search for
 * the word "hello" in the command-line arguments.

#include <search.h>
#include <string.h>
#include <stdio.h>

int compare( const void *arg1, const void *arg2 );

void main( unsigned int argc, char **argv )
   char **result;
   char *key = "hello";

   result = (char **)_lfind( &key, argv,
                      &argc, sizeof(char *), compare );
   if( result )
      printf( "%s found\n", *result );
      printf( "hello not found!\n" );

int compare(const void *arg1, const void *arg2 )
   return( _stricmp( * (char**)arg1, * (char**)arg2 ) );


[C:\code]lfind Hello
Hello found

Searching and Sorting Routines

See Also   bsearch, _lfind