ProgrammingHardWipro · Cognizant pattern

Assume a 64-bit LP64 ABI. What is printed?

Assume a 64-bit LP64 ABI. What is printed?
int compare(const void *a, const void *b) {
    return *(const int *)a - *(const int *)b;
}
int main(void) {
    int arr[5] = {5, 2, 8, 1, 9};
    qsort(arr, 5, sizeof(int), compare);
    printf("%d %d %d %d %d", arr[0], arr[1], arr[2], arr[3], arr[4]);
}
  1. A. 5 2 8 1 9
  2. B. 9 8 5 2 1
  3. C. 1 2 5 8 9
  4. D. Compile-time error: qsort's comparator must take int*, not void*

Correct answer: C. 1 2 5 8 9

qsort is generic over element type, so its comparator receives void* pointers that must be cast back to the actual element type (int here) before dereferencing. compare() returns a negative, zero, or positive value ordering elements for ascending sort; qsort uses that to sort arr into 1 2 5 8 9.

More C Programming questions

Exams that ask this topic