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?
- A. Pass the key as a struct and compare the whole struct with memcmp
- B. Compare the struct pointers directly with the < operator
- C. The comparator receives two void pointers and must cast both to const struct record * before reading the field
- 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
- Which comparator for qsort on int array is correct for ALL int values (no overflow, no wrong sign)?
- int m[3][4]; int f = &m[0][0]; Which expression refers to the same element as m[2][1]?
- int m[3][4]; What is sizeof(m) / sizeof(m[0][0])?
- int a[] = {1, 2}; int b[] = {3, 4}; int x = a, y = b; void swap(int p, int q) { int t = p; p = q; q = t; } After swap(&x, &y) runs, what…
- A recursive function is written as int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }. What is gcd(1071, 462)?
- Starting at n = 27, the loop while (n != 1) { n = (n % 2) ? 3 n + 1 : n / 2; steps++; } runs with int n. What is steps at the end?