Look up words in a sorted array of word–meaning pairs using bsearch and strcmp, reporting words that are not in the dictionary.
Solution
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct entry { const char *word, *meaning; };
static const struct entry dict[] = { /* sorted by word */
{"array", "fixed-size sequence of elements"},
{"macro", "text replaced by the preprocessor"},
{"pointer", "variable holding an address"},
{"struct", "group of named members"},
};
static int by_word(const void *key, const void *elem) {
return strcmp(key, ((const struct entry *) elem)->word);
}
int main(void) {
const char *queries[] = {"pointer", "lambda", "array"};
for (int i = 0; i < 3; i++) {
const struct entry *e = bsearch(queries[i], dict, sizeof dict / sizeof dict[0], sizeof dict[0], by_word);
printf("%-8s %s\n", queries[i], e ? e->meaning : "(not found)");
}
return 0;
}
Output Verified by compiling and running
pointer variable holding an address
lambda (not found)
array fixed-size sequence of elements
The key passed to bsearch does not need the element type: here it is the word itself, and the comparator compares it with each entry's word. Lookup takes O(log n) comparisons.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!