ProgrammingHard
A bsearch on a struct array returns NULL for a key that is actually present. Which is the most likely cause?
- A. The key was passed by pointer
- B. The array has more than 10 elements
- C. The array is not sorted with the same comparator that bsearch uses
- D. The array was allocated with malloc
Correct answer: C. The array is not sorted with the same comparator that bsearch uses
bsearch assumes the array order matches its comparator. If the sort used a different order, the probes can miss an existing key.
More C Programming questions
- A struct {int a; char b;} is used in an array of 3 elements on a platform with 4-byte int and natural alignment. What is sizeof(arr)?
- Using natural alignment, what is sizeof(struct { char c; short s; })?
- For struct { char name[4]; int v; } with a 4-byte int and natural alignment, what is sizeof of the struct?
- A selection sort on 5 elements (find the minimum, swap into place) makes how many key comparisons in total, for any input?
- Bubble sort with an early exit when a pass makes no swap is given an already sorted array of 5 elements. How many comparisons does it make?
- A sorted array of 10^6 keys answers 10^5 queries of the form 'how many keys lie in [L, R]'. Which approach is correct and fast enough?