Find an entry in a linear search table


#include <search.h>

void * lfind( const void *key, 
              const void *base,
              size_t *num, 
              size_t width,
              int (*compare)( 
                  const void *element1,
                  const void *element2 ) );


The object to search for.
A pointer to the first element in the table.
A pointer to an integer containing the current number of elements in the table.
The size of an element, in bytes.
A pointer to a user-supplied function that lfind() 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.



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


The lfind() function returns a pointer into a table indicating where an entry may be found.

Note: The lfind() function is the same as lsearch(), except that if the entry isn't found, it isn't added to the table, and a NULL pointer is returned.


A pointer to the matching element, or NULL if there's no match or an error occurred.


This example program lets you know if the first command-line argument is a C keyword (assuming you fill in the keywords array with a complete list of C keywords):

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

static const char *keywords[] = {
    /* . */
    /* . */
    /* . */

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

int main( int argc, const char *argv[] )
    size_t num = 5;
    char *ptr;

    if( argc <= 1 ) return EXIT_FAILURE;

    ptr = lfind( &argv[1], keywords, &num, sizeof(char **), compare );
    if( ptr == NULL ) {
        printf( "'%s' is not a C keyword\n", argv[1] );
        return EXIT_FAILURE;
    } else {
        printf( "'%s' is a C keyword\n", argv[1] );
        return EXIT_SUCCESS;
    /* You'll never get here. */
    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 ) );


POSIX 1003.1 XSI

Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes