#include <stdlib.h>
#include <stdio.h>
// void* bsearch(const void *key, const void *ptr, size_t count, size_t size,
// int (*comp)(const void*, const void*));
/*
key - pointer to the struct to search for
ptr - pointer to the array of structs
count - number of element in the array
size - size of each element in the array in bytes
comp - comparison function
*/
struct data
{
int n;
char const *lang;
} dat[] = { {1, "C"}, {2, "C++"}, {3, "C#"}, {4, "Java"}, {5, "PHP"} };
int data_cmp(void const *f_data, void const *s_data)
{
struct data const *const first = f_data;
struct data const *const second = s_data;
if (first->n < second->n) return -1;
else if (first->n > second->n) return 1;
else return 0;
}
int main(void)
{
struct data p_lang = { .n = 3 };
struct data const *p = bsearch(&p_lang, dat, sizeof dat / sizeof dat[0],
sizeof dat[0], data_cmp);
if (p) {
printf("Number %d is: %s\n", p->n, p->lang);
} else {
printf("Number %d not found\n", p_lang.n);
}
return 0;
}
/*
run:
Number 3 is: C#
*/