lsearch

De RAD Studio
Aller à : navigation, rechercher

Remonter à Stdlib.h - Index


Header File

stdlib.h

Category

Memory and String Manipulation Routines

Prototype

void *lsearch(const void *key, void *base, size_t *num, size_t width, int (_USERENTRY *fcmp)(const void *, const void *));

Description

Performs a linear search.

lsearch searches a table for information. Because this is a linear search, the table entries do not need to be sorted before a call to lsearch. If the item that key points to is not in the table, lsearch appends that item to the table.

  • base points to the base (0th element) of the search table.
  • num points to an integer containing the number of entries in the table.
  • width contains the number of bytes in each entry.
  • key points to the item to be searched for (the search key).

The function fcmp must be used with the _USERENTRY calling convention.

The argument fcmp points to a user-written comparison routine, that compares two items and returns a value based on the comparison.

To search the table, lsearch makes repeated calls to the routine whose address is passed in fcmp.

On each call to the comparison routine, lsearch passes two arguments:

key

a pointer to the item being searched for

elem

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

lsearch 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.

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 **arg1, char **arg2)
 {
    return(strcmp(*arg1, *arg2));
 }
 int addelem(char **key)
 {
    int oldn = ncolors;
    lsearch(key, colors, (size_t *)&ncolors, sizeof(char *),
      (int(*)(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
    {
       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;
 }



Portability



POSIX Win32 ANSI C ANSI C++

+