/* search.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char last[16];
char first[11];
char phone[13];
int age;
};
static int comp(const void *, const void *);
main()
{
int i;
struct person *p;
static struct person key = {"","","555-1965",0};
static struct person people[] =
{{"Ford","Henry","555-1903",98},
{"Lincoln","Abraham","555-1865",161},
{"Ford","Edsel","555-1965",53},
{"Trump","Donald","555-1988",49}};
/* Sort */
qsort(people, 4, sizeof people[0], comp);
/* Search */
p = bsearch(&key, people, 4, sizeof people[0], comp);
if (p != NULL)
{
printf(
"%s, %s, %s, %d\n",
p->last,
p->first,
p->phone,
p->age
);
}
else
puts("Not found");
return 0;
}
/* Compare function: */
static int comp(const void *x, const void *y)
{
struct person *pl = (struct person *) x;
struct person *p2 = (struct person *) y;
return strcmp(p1->phone,p2->phone);
}
/* Output: */
Ford, Edsel, 555-1965, 53
/* End of File */