Function name : lsearch
Header file : <stdlib.h>
Function prototype : void* lsearch(void* key,void* district,size_t *n,size_t m,
int (*func)(const void*,const void*));
Function : Used to perform a linear search from beginning to end within a given area
Parameters : void* key pointer to the keyword to be found
void* district points to the starting address of the area to be searched
size_t *n Find the number of area elements
size_t m finds the size of each element in the range
int (*func)(const void*,const void*) A pointer to a function. This function is used to compare the sizes of two elements.
Return value : If key data is found in the search area, the address of the found element is returned;
If the searched data is not in the search area, add it to the search area, and then return the added address;
Program example : Use this function to linearly search for element 27 in array a and add the new element to the array
#include<stdio.h>#include<stdlib.h>typedefint(*fc)(constvoid*,constvoid*);intcompare(constvoid*p1,constvoid*p2){//Compare the size of two numbers int*pi1= (int*)p1;int*pi2=(int*)p2;return(*pi1-*pi2);}intmain(void){intarr[5]={25,14,29,68,55};size_tn= 5;intkey=27;fcf=compare;int*result=(int*)lsearch(&key,arr,&n,sizeof(int),f);if(result){printf(Number%disfoundn,key); }else{printf(Number%disnotfoundn,key);}return0;}
Running results
Number27isfound