ProgrammingVery hard
An array struct P *ps[] of pointers to records is to be sorted by an int field k with qsort. Which comparator is correct?
- A. int cmp(const void *a, const void *b) { int x = (*(struct P *const *)a)->k, y = (*(struct P *const *)b)->k; return (x > y) - (x < y); }
- B. int cmp(const void *a, const void *b) { return ((struct P *)a)->k - ((struct P *)b)->k; }
- C. int cmp(const void *a, const void *b) { return *(struct P *const *)a - *(struct P *const *)b; }
- D. int cmp(const void *a, const void *b) { int x = (*(struct P *const *)a)->k; return x; }
Correct answer: A. int cmp(const void *a, const void *b) { int x = (*(struct P *const *)a)->k, y = (*(struct P *const *)b)->k; return (x > y) - (x < y); }
qsort passes the address of each element, which is a pointer to a struct P pointer. One dereference gives the struct pointer, and -> reaches the key. The other versions treat the slot as the struct, subtract pointers, or ignore the second element.
More C Programming questions
- For struct R { char c; short s; int i; } with natural alignment (char 1, short 2, int 4), what is sizeof(struct R)?
- Assume natural alignment with 4-byte int. What is sizeof(struct R[5]) where struct R is the eight-byte type from the previous record?
- struct Q { char name[6]; double score; char tag; }; with 8-byte double and natural alignment. What is sizeof(struct Q)?
- Assume natural alignment: char 1, double 8. What is sizeof(struct T) for struct T { char a; double d; char b[3]; }?
- Binary search with lo = 0, hi = n - 1 on n = 1000 sorted records, looking for a key not in the array, performs how many probes at most?
- Insertion sort is applied to a = {5, 2, 4, 6, 1, 3} and each element moved one slot to the right while shifting counts as one move. How…