#include <stdlib.h>void *bsearch(const void *key, const void *base, size_t nel, size_t size, int (*compar)(const void *, const void *));
This program reads in strings and either finds the corresponding node and prints out the string and its length, or prints an error message.
#include <stdio.h> #include <stdlib.h> #include <string.h>struct node { /* these are stored in the table */ char *string; int length; }; static struct node table[] = /* table to be searched */ { { "asparagus", 10 }, { "beans", 6 }, { "tomato", 7 }, { "watermelon", 11 }, };
main() { struct node *node_ptr, node; /* routine to compare 2 nodes */ static int node_compare(const void *, const void *); char str_space[20]; /* space to read string into */
node.string = str_space; while (scanf("%20s", node.string) != EOF) { node_ptr = bsearch( &node, table, sizeof(table)/sizeof(struct node), sizeof(struct node), node_compare); if (node_ptr != NULL) { (void) printf("string = %20s, length = %d\n", node_ptr->string, node_ptr->length); } else { (void)printf("not found: %20s\n", node.string); } } return(0); }
/* routine to compare two nodes based on an */ /* alphabetical ordering of the string field */ static int node_compare(const void *node1, const void *node2) { return (strcmp( ((const struct node *)node1)->string, ((const struct node *)node2)->string)); }
The comparison function need not compare every byte, so arbitrary data may be contained in the elements in addition to the values being compared.
If the number of elements in the table is less than the size reserved for the table, nel should be the lower number.