LSEARCH(3,L) AIX Technical Reference LSEARCH(3,L)
-------------------------------------------------------------------------------
lsearch, lfind
PURPOSE
Performs a linear search and update.
LIBRARY
Standard C Library (libc.a)
SYNTAX
char *lsearch (key, base, nelp, size, compar)
char *key
char *base
unsigned int *nelp;
size_t size;
int (*compar) ( );
char *lfind (key, base, nelp, size, compar)
char *key
char *base
unsigned int *nelp;
size_t size;
int (*compar) ( );
DESCRIPTION
The lsearch subroutine performs a linear search generalized from Donald E.
Knuth's The Art of Computer Programming, Volume 3, 6.1, Algorithm S.(*) It
returns a pointer into a table indicating where a datum can be found. If the
datum does not occur, it is added at the end of the table.
The key parameter points to the datum to be sought in the table. The base
parameter points to the first element in the table. The nelp parameter points
to an integer containing the current number of elements in the table. This
integer is incremented if the datum is added to the table. The compar
parameter is the name of the comparison function that you must supply (strcmp,
for example). It is called with two parameters that point to the elements
being compared. The compar function must return a value of 0 if the elements
are equal and nonzero if they are not equal.
The lfind subroutine is identical to lsearch, except that if the datum is not
found, then it is not added to the table. Instead, a NULL pointer is returned
in this case.
---------------
(*) Reading, Massachusetts: Addison-Wesley, 1981.
Processed November 7, 1990 LSEARCH(3,L) 1
LSEARCH(3,L) AIX Technical Reference LSEARCH(3,L)
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. Although it is
declared as type pointer-to-character, the value returned should be cast into
type pointer-to-element.
The comparison function need not compare every byte; therefore, the elements
can contain arbitrary data in addition to the values being compared.
Warning: Undefined results can occur if there is not enough room in the table
for lsearch to add a new item.
EXAMPLE
The following code fragment reads up to "TABSIZE" strings, each of which is up
to "ELSIZE" bytes long, and stores them into a table, eliminating duplicates.
#include <stdio.h>
#define TABSIZE 50
#define ELSIZE 120
char *lsearch();
int strcmp();
char line[ELSIZE], tab[TABSIZE][ELSIZE];
unsigned nel = 0;
...
while (fgets(line, ELSIZE, stdin) != NULL && nel < TABSIZE)
{
(void) lsearch(line, (char *)tab, &nel, ELSIZE, strcmp);
}
...
RELATED INFORMATION
In this book: "bsearch," "hsearch, hcreate, hdestroy," and "tsearch, tdelete,
twalk."
Processed November 7, 1990 LSEARCH(3,L) 2