ProgrammingVery hard

For a struct array sorted by an int key, which bsearch call is correct to find a record with key k?

  1. A. bsearch(k, recs, n, sizeof k, cmp), passing the int itself
  2. B. bsearch(&key, recs, n, sizeof recs[0], cmp), where key is a struct with its key field set to k and cmp compares those keys
  3. C. bsearch(&k, recs, sizeof recs, sizeof recs[0], cmp), passing the byte size of the array as n
  4. D. bsearch(recs, &k, n, sizeof recs[0], cmp), with the arguments swapped

Correct answer: B. bsearch(&key, recs, n, sizeof recs[0], cmp), where key is a struct with its key field set to k and cmp compares those keys

bsearch takes a pointer to the key, the base address, the element count and the element size; the comparator receives the key pointer as its first argument. Using a struct key with its key field set to k lets one comparator serve both qsort and bsearch. The other calls pass a non-pointer key, a byte count instead of an element count, or swapped key/base.

More C Programming questions

Exams that ask this topic