-
header file : #include <search.h>
reference :
Defining how to compare two int objects:
int
compare_ints (const void *a, const void *b)
{
const int *da = (const int *) a;
const int *db = (const int *) b;
return (*da > *db) - (*da < *db);
}
return :
- negative if a “less” than b
- zero if a and b are "equal"
- positive if a "greater" than b
Inside C code
#include<stdio.h>
#include<search.h>
#define ARRAYMAX 10
int
compare_ints (const void *a, const void *b)
{
const int *da = (const int *) a;
const int *db = (const int *) b;
return (*da > *db) - (*da < *db);
}
int
main(void)
{
int *result;
int data_array[ARRAYMAX] = {1,2,3,4,5,6,7,8,9,10};
int array_size =ARRAYMAX;
int key = 9;
result = (int*) lfind(&key, &data_array, &array_size, sizeof (int), compare_ints);
if(result)
printf("key %d is found in the data array.\n", key);
else
printf("key %d is not in the data array.\n", key);
return 0;
}