aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorBenedict Reuschling <bcr@FreeBSD.org>2019-05-15 15:54:27 +0000
committerBenedict Reuschling <bcr@FreeBSD.org>2019-05-15 15:54:27 +0000
commit15c9c06e6a25a84cffdf0e2c6460119b239dbe55 (patch)
tree67070d55b6f334e5e42636c2b3889075b8c0e526 /lib
parent6aa63d8dbe8db841d2344092e2e90323b7f8b860 (diff)
downloadsrc-15c9c06e6a25a84cffdf0e2c6460119b239dbe55.tar.gz
src-15c9c06e6a25a84cffdf0e2c6460119b239dbe55.zip
Add small EXAMPLE section to bsearch.3.
Submitted by: fernape (via Phabricator) Reviewed by: bcr, jilles, dab Approved by: bcr (man pages), jilles (src) MFC after: 3 days Differential Revision: https://reviews.freebsd.org/D19902
Notes
Notes: svn path=/head/; revision=347617
Diffstat (limited to 'lib')
-rw-r--r--lib/libc/stdlib/bsearch.357
1 files changed, 56 insertions, 1 deletions
diff --git a/lib/libc/stdlib/bsearch.3 b/lib/libc/stdlib/bsearch.3
index 2fdf2c4842c0..87f4cc862204 100644
--- a/lib/libc/stdlib/bsearch.3
+++ b/lib/libc/stdlib/bsearch.3
@@ -32,7 +32,7 @@
.\" @(#)bsearch.3 8.3 (Berkeley) 4/19/94
.\" $FreeBSD$
.\"
-.Dd February 22, 2013
+.Dd May 15, 2019
.Dt BSEARCH 3
.Os
.Sh NAME
@@ -83,6 +83,61 @@ The
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 searches people by age in a sorted array:
+.Bd -literal
+#include <assert.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+struct person {
+ char name[5];
+ int age;
+};
+
+int
+compare(const void *key, const void *array_member)
+{
+ int age = (intptr_t) 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);
+
+ friend = bsearch((void *)22, &friends, array_size, sizeof(struct person), compare);
+ assert(strcmp(friend->name, "paul") == 0);
+ printf("name: %s\enage: %d\en", friend->name, friend->age);
+
+ friend = bsearch((void *)25, &friends, array_size, sizeof(struct person), compare);
+ assert(strcmp(friend->name, "fred") == 0 || strcmp(friend->name, "anne") == 0);
+ printf("name: %s\enage: %d\en", friend->name, friend->age);
+
+ friend = bsearch((void *)30, &friends, array_size, sizeof(struct person), compare);
+ assert(friend == NULL);
+ printf("friend aged 30 not found\en");
+
+ return (EXIT_SUCCESS);
+}
+.Ed
.Sh SEE ALSO
.Xr db 3 ,
.Xr lsearch 3 ,