perform a linear search in an array
#include <search.h> void *lfind( const void *key, const void *base, unsigned *num, unsigned width, int (*compare)( const void *element1, const void *element2 ) );
The lfind() function performs a linear search for the value key in the array of num elements pointed to by base. Each element of the array is width bytes in size. The argument compare is a pointer to a user-supplied routine that will be called by lfind() to determine the relationship of an array element with the key. One of the arguments to the compare function will be an array element, and the other will be key.
The compare function should return 0 if element1 is identical to element2, and nonzero if the elements are not identical.
If key is found, lfind() returns a pointer to the array element in base that matches it. If key isn't found, the function returns NULL.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <search.h> static const char *keywords[] = { "auto", "break", "case", "char", /* . */ /* . */ /* . */ "while" }; void main( int argc, const char *argv[] ) { unsigned num = 5; int compare( const void *, const void * ); if( argc <= 1 ) exit( EXIT_FAILURE ); if( lfind( &argv[1], keywords, &num, sizeof(char **), compare ) == NULL ) { printf( "'%s' is not a C keyword\n", argv[1] ); exit( EXIT_FAILURE ); } else { printf( "'%s' is a C keyword\n", argv[1] ); exit( 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 ) ); }
WATCOM
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |