ProgrammingHard
Given char *names[] holding strings, which qsort comparator sorts them alphabetically?
- A. int cmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
- B. int cmp(const void *a, const void *b) { return strcmp((const char *)a, (const char *)b); }
- C. int cmp(const void *a, const void *b) { return *(char *)a - *(char *)b; }
- D. int cmp(const void *a, const void *b) { return strcmp(a, b); }
Correct answer: A. int cmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
qsort passes pointers to the array elements, which here are char pointers. The comparator must dereference once before calling strcmp. The other versions compare the slots' addresses or single bytes.
More C Programming questions
- char d[6] = "abc"; / we want strncat(d, "defgh", 5) with no overflow / What is the smallest size d needs?
- char b[16]; sprintf(b, "%d%%", 50); printf("%zu", strlen(b)); What is printed?
- printf("%c", 321); What is printed?
- char a[20], b[20]; / stdin: "hi therennextn" / scanf("%s", a); fgets(b, sizeof b, stdin); What is stored in b?
- char w[] = "ab", z[2] = "ab"; printf("%zu", sizeof w + sizeof z); What is printed?
- For a string s of length up to 2 x 10^5 stored in a char array, which in-place reversal is correct and fast enough?