[Previous] [Contents] [Next]

lsearch()

Perform a linear search in an array

Synopsis:

#include <search.h>
              
void * lsearch( const void * key,
               const void * base,
               unsigned * num,
               unsigned width,
               int ( * compare)( 
                   const void * element1,
                   const void * element2 ) );

Library:

libc

Description:

The lsearch() function returns a pointer into a table indicating where an entry may be found. If the entry doesn't occur, it's added at the end of the table.

key
Object to search for.
base
Points to the first element in the table.
num
Points to an integer containing the current number of elements in the table.
width
Size of an element in bytes.
compare
Points to a user-supplied function called by lsearch() to compare an array element with the key. The compare function is called with key and one of the array elements as arguments.

The compare function must return 0 if element1 equals element2, or nonzero if the elements aren't equal.


Caution: If key isn't found, it's added to the end of the array and num is incremented.

Returns:

A match was found
A pointer to the matching element.
No match was found
A pointer to the newly added element.
An error occurred
A null pointer.

Examples:

This program builds an array of pointers to the argv arguments by searching for them in an array of NULL pointers. Because none of the items will be found, they'll all be added to the array.

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

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

int main( int argc, const char **argv )
{
    int i;
    unsigned num = 0;

    char **array = (char **)calloc( argc, sizeof(char **) );

    for( i = 1; i < argc; ++i ) {
        lsearch( &argv[i], array, &num, sizeof(char **), compare );
    }
    
    for( i = 0; i < num; ++i ) {
        printf( "%s\n", array[i] );
    }
    
    return EXIT_SUCCESS;
}

int compare( const void *op1, const void *op2 )
{
    const char **p1 = (const char **) op1;
    const char **p2 = (const char **) op2;

    return( strcmp( *p1, *p2 ) );
}

Using the program above, this input:

one two one three four

produces the output:

one
two
three
four

Classification:

Standard Unix

Safety:
Cancellation point No
Interrupt handler Yes
Signal handler Yes
Thread Yes

See also:

bsearch(), lfind()


[Previous] [Contents] [Next]