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 ) );
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 lsearch() function searches a linear table and returns a pointer into the table indicating where the entry was found.
If key isn't found, it's added to the end of the array and num is incremented. |
A pointer to the element that was found or created, or NULL if an error occurred.
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 |