lsearch [ HP C/iX Library Reference Manual ] MPE/iX 5.0 Documentation
HP C/iX Library Reference Manual
lsearch
Performs a linear search and update.
Syntax
#include <stdio.h>
#include <search.h>
char *lsearch ((char *)key, (char *)base, nelp,
sizeof(*key), compar)
unsigned *nelp;
int (*compar)( );
Parameters
key A pointer to the value to be found in the table.
base A pointer to the first element in the table.
nelp A pointer to an integer containing the current number of
elements in the table. This integer is incremented if the
item is added to the table.
width The width of each table row.
compar A pointer to a comparison function that you must supply,
such as strcmp. It is called with two arguments that point
to the elements being compared. The function must return
zero if the elements are equal, and nonzero if they are not
equal.
Return Values
x A character pointer to the element being sought, whether
newly added or pre-existing in the table.
Description
The lsearch function is a linear search function generalized from Knuth
Algoritm S (6.1).(1)
FOOTNOTE (1) The Art of Computer Programming, Vol.3 (Sorting and
Searching) by Donald Ervin Knuth (Reading, Mass:Addison-Wesley,
1973).
It returns a pointer into a table indicating where an item may be found.
If the item does not occur, it is added at the end of the table.
The pointers to the key and the element at the base of the table should
be of type pointer-to-element, and cast to type pointer-to-character.
The comparison function does not need to compare every byte, so arbitrary
data may be contained in the elements in addition to the values being
compared.
The value returned is declared as type pointer-to-character, but should
be cast as type pointer-to-element.
Undefined results can occur if there is not enough room in the table to
add a new item.
Example
This fragment reads in TABSIZE strings of length ELSIZE and stores them
in a table, eliminating duplicates.
#include <stdio.h>
#include <search.h>
#define TABSIZE 50
#define ELSIZE 120
char line[ELSIZE], tab[TABSIZE][ELSIZE], *lsearch( );
unsigned nel = 0;
int strcmp( );
:
while (fgets(line, ELSIZE, stdin) != NULL&&
nel< TABSIZE)
(void) lsearch(line, (char *)tab,&nel,
ELSIZE, strcmp);
:
See Also
lfind()
MPE/iX 5.0 Documentation