perform a linear search in an array
#include <search.h> void *lsearch( const void *key, void *base, unsigned *num, unsigned width, int (*compare)( const void *element1, const void *element2 ) );
The lsearch() 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 is called by lsearch() to determine the relationship of an array element with the key. One of the arguments to the compare function is an array element, and the other is key.
The compare function should return 0 if element1 is identical to element2, and nonzero if the elements aren't identical.
If the key value is not found in the array, then it is added to the end of the array, and the number of elements is incremented.
A pointer to the array element in base that matches key if it was found, or the newly added entry if key wasn't found.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <search.h> void main( int argc, const char *argv[] ) { int i; unsigned num = 0; char **array = (char **)calloc( argc, sizeof(char **) ); int compare( const void *, const void * ); 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] ); } } int compare( const void *op1, const void *op2 ) { const char **p1 = (const char **) op1; const char **p2 = (const char **) op2; return( strcmp( *p1, *p2 ) ); } /* With input: one two one three four */
produces the output:
one two three four
WATCOM
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | No |
Thread | Yes |