ProgrammingHard

A bsearch call uses a key of type int but the array holds struct records with an int field. What is the correct way to compare?

  1. A. Pass the key as a struct and compare the whole struct with memcmp
  2. B. Compare the struct pointers directly with the < operator
  3. C. The comparator receives two void pointers and must cast both to const struct record * before reading the field
  4. D. Cast the key to char * and compare bytes

Correct answer: C. The comparator receives two void pointers and must cast both to const struct record * before reading the field

bsearch passes pointers. The comparator must convert each pointer to the element type before reading its key field, so the key pointer needs the same kind of cast.

More C Programming questions

Exams that ask this topic