LearnFrenzy
Sign in Take a free test

C Library Functions · Library Function Programs · Question 3

Dictionary lookup of words with bsearch in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links