lsearch() — Linear search and update

Standards

Standards / Extensions C or C++ Dependencies

XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _XOPEN_SOURCE
#include <search.h>

void *lsearch(const void *key, void *base, size_t *nelp, 
              size_t width,
              int (*compar)(const void *, const void *));

General description

The lsearch() function is a linear search routine. It returns a pointer into a table indicating where an entry may be found. If the entry does not occur, it is added at the end of the table. The key argument points to the entry to be sought in the table. The base argument points to the first element in the table. The width argument is the size of an element in bytes. The nelp argument points to an integer containing the current number of elements in the table. The integer to which nelp points is incremented if the entry is added to the table. The compar argument points to a comparison function which the user must supply (strcmp(), for example). It is called with two arguments that point to the elements being compared. The function must return 0 if the elements are equal and nonzero otherwise.

Special behavior for C++: Because C and C++ linkage conventions are incompatible, lsearch() cannot receive a C++ function pointer as the comparator argument. If you attempt to pass a C++ function pointer to lsearch(), the compiler will flag it as an error. You can pass a C or C++ function to lsearch() by declaring it as extern "C".

Returned value

If the searched for entry is found, lsearch() returns a pointer to it.

If not found, lsearch() returns a pointer to the newly added element. A NULL pointer is returned in case of error.

No errors are defined.

Related information