Updated: April 19, 2023 |
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 comparison function must return 0 if element1 equals element2, or a nonzero value if the elements aren't equal.
libc
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.
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[] = { "auto", "break", "case", "char", /* . */ /* . */ /* . */ "while" }; 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 ) ); }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |