lsearch()

Updated: April 19, 2023

Perform a linear search in an array

Synopsis:

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

Arguments:

key
The object to search for.
base
A pointer to the first element in the table.
num
A pointer to an integer containing the current number of elements in the table.
width
The size of an element, in bytes.
compare
A pointer to a user-supplied function that lsearch() calls to compare an array element with the key. The arguments to the comparison function are:
  • element1 — the same pointer as key
  • element2 — a pointer to one of the array elements.

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

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The lsearch() function searches a linear table and returns a pointer into the table indicating where the entry was found.

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

Returns:

A pointer to the element that was found or created, or NULL if an error occurred.

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;
    size_t 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:

POSIX 1003.1 XSI

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