ProgrammingVery hard
For a struct array sorted by an int key, which bsearch call is correct to find a record with key k?
- A. bsearch(k, recs, n, sizeof k, cmp), passing the int itself
- 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
- C. bsearch(&k, recs, sizeof recs, sizeof recs[0], cmp), passing the byte size of the array as n
- 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
- A bsearch on a struct array returns NULL for a key that is actually present. Which is the most likely cause?
- 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?