ProgrammingVery hardTCS NQT · Infosys

What is printed?

What is printed?
#include <stdio.h>
#include <stdlib.h>
struct Item { int id; char tag; };
int cmp(const void *k, const void *e) {
    const int *key = k;
    const struct Item *it = e;
    return (*key > it->id) - (*key < it->id);
}
int main(void) {
    struct Item arr[] = {{2, 'a'}, {4, 'b'}, {7, 'c'}, {9, 'd'}, {12, 'e'}};
    int key = 7;
    struct Item *r = bsearch(&key, arr, 5, sizeof arr[0], cmp);
    printf("%ld", (long)(r - arr));
}
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 4

Correct answer: B. 2

bsearch needs the array sorted by id, which it is, and it returns a pointer to the element with id 7 at index 2. Passing the key in the wrong position would fail, but the comparator here handles it correctly.

More C Programming questions

Exams that ask this topic