lsearch
Performs a linear search.
Defined in header <stdlib.h>
Syntax
#include <stdlib.h>
void *lsearch(const void *key, void *base, size_t *num, sizet width,
int (*/cmp)(const void *, const void *));
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ |
Remarks
Isearch searches a table for information. Because this is a linear search, the table entries do not need to be sorted before a call to [search. If the item that key points to is not in the table, Isearch appends that item to the table.
Q foflse points to the base (0th element) of the search table. □ num. points to an integer containing the number of entries in the table. D width contains the number of bytes in each entry. H key points to the item to be searched for (the search key).
The argument fcmp points to a user-written comparison routine, which compares two items and returns a value based on the comparison.
To search the table, Isearch makes repeated calls to the routine whose address is passed in/cm/7.
On each call to the comparison routine, Isearch passes two arguments: key, a pointer to the item being searched for, and elem, a pointer to the element of base being compared.
fcmp is free to interpret the search key and the table entries in any way.
Return value
Isearch returns the address of the first entry in the table that matches the search key.
If the search key is not identical to *elem, fcmp returns a nonzero integer. If the search key is identical to *elem, fcmp returns 0.
See also
Example
#include <stdlib.h>
#include <stdio.h>
#include <string.h> /* for strcmp declaration */
/* initialize number of colors */
char *colors[10] = { "Red", "Blue" "Green" };
int ncolors = 3;
int colorscmp(char **argl, char **arg2) {
return (strcmp(*argl, *arg2));
int addelem(char *key) {
int oldn = ncolors;
lsearch(key, colors, (size_t *) tncolors, sizeof(char (mt
(const void *, const void *)) colorscmp);
return(ncolors == oldn) ;
int main(void)
{
int i;
char *key = "Purple";
if (addelem(key))
printf("%s already in colors table\n", key);
else {
strcpy(colors [ncolors-1],key);
printf("%s added to colors table\n", key);
}
printf("The colors:\n");
for (i = 0; i < ncolors; i++)
printf("%s\n", colors[i]);
return 0;
Differences from modern implementations
Nothing recorded yet.
Modern references
These are search links, not yet checked by hand.
Extraction notes
- heading `Isearch` read as `lsearch`
Stable link: /3.1/stdlib.h/lsearch/
· short form /3.1/lsearch/