Page Menu
Home
FreeBSD
Search
Configure Global Search
Log In
Files
F147027180
D19902.id57774.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Flag For Later
Award Token
Size
1 KB
Referenced Files
None
Subscribers
None
D19902.id57774.diff
View Options
Index: lib/libc/stdlib/bsearch.3
===================================================================
--- lib/libc/stdlib/bsearch.3
+++ lib/libc/stdlib/bsearch.3
@@ -93,26 +93,28 @@
#include <string.h>
struct person {
- char name[5];
- int age;
+ const char *name;
+ int age;
};
int
-compare(const void *key, const void *array_member)
+compare(const void *a, const void *b)
{
- int age = (intptr_t) key;
- struct person person = *(struct person *) array_member;
+ int age;
+ struct person person_b;
- return (age - person.age);
+ age = *(const int *)a;
+ person_b = *(const struct person *)b;
+
+ return (age - person_b.age);
}
int
-main()
+main(void)
{
struct person *friend;
-
/* Sorted array */
- struct person friends[6] = {
+ const struct person friends[] = {
{ "paul", 22 },
{ "anne", 25 },
{ "fred", 25 },
@@ -121,21 +123,27 @@
{ "bill", 50 }
};
- size_t array_size = sizeof(friends) / sizeof(struct person);
+ const size_t len = sizeof(friends) / sizeof(friends[0]);
- friend = bsearch((void *)22, &friends, array_size, sizeof(struct person), compare);
+ int age = 22;
+ friend = bsearch(&age, friends, len, sizeof(friends[0]), 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);
+ age = 25;
+ friend = bsearch(&age, friends, len, sizeof(friends[0]), compare);
+
+ /*
+ * For multiple elements with the same key, it is implementation
+ * defined which will be returned
+ */
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);
+ age = 30;
+ friend = bsearch(&age, friends, len, sizeof(friends[0]), compare);
assert(friend == NULL);
printf("friend aged 30 not found\en");
-
- return (EXIT_SUCCESS);
}
.Ed
.Sh SEE ALSO
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Sun, Mar 8, 5:44 PM (19 h, 56 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
29411812
Default Alt Text
D19902.id57774.diff (1 KB)
Attached To
Mode
D19902: bsearc.3: Add EXAMPLES section
Attached
Detach File
Event Timeline
Log In to Comment