![]() |
![]() |
![]() |
Perform a linear search in an array
#include <search.h> void * lsearch( const void * key, const void * base, unsigned * num, unsigned width, int ( * compare)( const void * element1, const void * element2 ) );
libc
The lsearch() function returns a pointer into a table indicating where an entry may be found. If the entry doesn't occur, it's added at the end of the table.
The compare function must return 0 if element1 equals element2, or nonzero if the elements aren't equal.
![]() |
If key isn't found, it's added to the end of the array and num is incremented. |
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; unsigned 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
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | Yes |
Signal handler | Yes |
Thread | Yes |
![]() |
![]() |
![]() |