ProgrammingVery hardCompetitive coding (CP)

What index is printed when bsearch looks up "cat" in the sorted array {"ant", "bee", "cat", "dog"}?

What index is printed when bsearch looks up "cat" in the sorted array {"ant", "bee", "cat", "dog"}?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *k, const void *e) {
    return strcmp((const char *)k, *(const char *const *)e);
}
int main(void) {
    const char *w[] = {"ant", "bee", "cat", "dog"};
    const char **r = bsearch("cat", w, 4, sizeof w[0], cmp);
    printf("%ld", (long)(r - w));
}
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 0

Correct answer: C. 2

The array is sorted, and bsearch finds "cat" at index 2 after comparing it with "bee" and then "cat".

More C Programming questions

Exams that ask this topic