ProgrammingVery hard
A comparator for qsort is written as int cmp(const void *a, const void *b) { return ((const struct P *)a)->k > ((const struct P *)b)->k; }. Which statement is correct?
- A. It returns only 0 or 1 and never a negative value, so the sort cannot order elements that should go first
- B. It is correct, since greater-than gives the sign
- C. It is correct, but only when the array has two elements
- D. It is a compile error because > cannot compare ints
Correct answer: A. It returns only 0 or 1 and never a negative value, so the sort cannot order elements that should go first
qsort needs a negative, zero or positive result. A boolean returns 0 or 1, so the order it implies is incomplete and the result is wrong.
More C Programming questions
- For a struct array sorted by an int key, which bsearch call is correct to find a record with key k?
- 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?