Index: bsearch.3 =================================================================== --- bsearch.3 +++ bsearch.3 @@ -83,6 +83,60 @@ function returns a pointer to a matching member of the array, or a null pointer if no match is found. If two members compare as equal, which member is matched is unspecified. +.Sh EXAMPLES +A sample program that searchs people by age in a sorted array: +.Bd -literal +#include +#include + +struct person { + char name[5]; + int age; +}; + +int +compare(const void *key, const void *array_member) +{ + int age = (int) key; + struct person person = *(struct person *) array_member; + + return (age - person.age); +} + +int +main() +{ + struct person *friend; + + /* Sorted array */ + struct person friends[6] = { + { "paul", 22 }, + { "anne", 25 }, + { "fred", 25 }, + { "mary", 27 }, + { "mark", 35 }, + { "bill", 50 } + }; + + size_t array_size = sizeof(friends) / sizeof(struct person); + + /* returns paul */ + friend = bsearch((void *)22, &friends, array_size, sizeof(struct person), compare); + printf("name: %s\nage: %d\n", friend->name, friend->age); + + /* Unspecified, could be fred or anne. Probably the first found, though */ + friend = bsearch((void *)25, &friends, array_size, sizeof(struct person), compare); + printf("name: %s\nage: %d\n", friend->name, friend->age); + + /* Not found. friend == NULL */ + friend = bsearch((void *)30, &friends, array_size, sizeof(struct person), compare); + if (friend == NULL) { + printf("friend aged 30 not found\n"); + } + + return (EXIT_SUCCESS); +} +.Ed .Sh SEE ALSO .Xr db 3 , .Xr lsearch 3 ,