The report prints topics in alphabetical order, with one line per topic. Grouping is easy once equal topics are next to each other, and sorting puts them there. You do not need to write a sorting algorithm: qsort from <stdlib.h> sorts any array in place. What you must write is the comparator, a callback that answers "which of these two elements comes first?" qsort trusts that answer completely. A comparator that overflows, or that gives inconsistent answers, does not just produce a slightly wrong order: the standard places no requirements on what qsort does with it.
Predict and run
Read the program before pressing Run. Write down its output and explain what the comparator returns for 30 and 10.
#include <stdio.h>
#include <stdlib.h>
int compare_ints(const void *left, const void *right) {
const int *a = left; const int *b = right;
return (*a > *b) - (*a < *b);
}
int main(void) {
int values[3] = {30, 10, 20};
qsort(values, 3, sizeof *values, compare_ints);
for (size_t i = 0; i < 3; ++i) { printf("%d\n", values[i]); }
return 0;
}Check your prediction
10
20
30For 30 and 10, the first comparison, (*a > *b), is 1 and the second is 0, so the result is 1: a positive value means "left belongs after right". Equal values give 0 - 0, which is 0.
What qsort sees
qsort(base, count, size, compare) knows nothing about your element type. It sees count blocks of size bytes starting at base, and it moves them around as raw bytes. To decide an order, it passes your comparator two const void * pointers, each pointing at one element inside the array. The comparator converts them back to the real element type, here const int *, and returns a negative number, zero or a positive number. sizeof *values ties the element size to the array's type, the same habit as with malloc.
Do not compare by subtracting
return *a - *b; is a common shortcut, and it has the right sign for small numbers. But signed subtraction can overflow, and signed overflow is undefined behavior:
int compare_bad(const void *left, const void *right) {
const int *a = left; const int *b = right;
return *a - *b; /* INT_MAX - (-1) overflows */
}On typical hardware the result wraps to a negative number, so the comparator claims INT_MAX comes before -1. Subtracting two comparison results, as in compare_ints above, only compares, so it cannot overflow, and it works for long, size_t and double too.
The comparator must tell the truth
qsort assumes the answers form a consistent order. If compare(x, y) is negative, compare(y, x) must be positive; if x comes before y and y before z, x must come before z; and the same pair must get the same answer every time. A comparator that returns a random value, reads changing global state, or forgets a case breaks those rules, and the standard makes the result undefined: elements may end up out of order, and some implementations can even read outside the array. Keep comparators pure: no side effects, no printing, no hidden state.
Sorting records by two keys
Records sort by topic first. When topics tie, compare minutes, so the order of equal-topic records is fully decided:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char topic[24]; int minutes; } Record;
static int compare_records(const void *left, const void *right) {
const Record *a = left;
const Record *b = right;
int topic = strcmp(a->topic, b->topic);
if (topic != 0) { return topic; }
return (a->minutes > b->minutes) - (a->minutes < b->minutes);
}
int main(void) {
Record records[4] = {{"reading", 25}, {"coding", 40}, {"reading", 10}, {"art", 30}};
qsort(records, 4, sizeof *records, compare_records);
for (size_t i = 0; i < 4; ++i) {
printf("%s %d\n", records[i].topic, records[i].minutes);
}
return 0;
}art 30
coding 40
reading 10
reading 25qsort is not stable: records that compare equal may come out in any order, and that order can differ between C libraries. The secondary key makes the output the same everywhere. Records that are equal in both fields are identical, so their order cannot be seen.
Sort a copy when order matters
qsort rearranges the array you give it. If the collection's insertion order matters to other operations, such as "remove the second record I entered", sorting it in place for a report would break them. The project's analyzer_report allocates a temporary block, copies the records into it with memcpy, sorts the copy, prints, and frees the copy. That costs one allocation, which can fail, and is why the report itself can return ANALYZER_NOMEM.
Practice
Your turn
Write by_minutes_desc, a comparator that orders records by minutes from largest to smallest and breaks ties by topic in alphabetical order. Sort the starter's five records and print them. Expected output: coding 40, art 25, reading 25, math 10, reading 10.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char topic[24]; int minutes; } Record;
/* Write by_minutes_desc here. */
int main(void) {
Record records[5] = {
{"reading", 10}, {"reading", 25}, {"coding", 40}, {"math", 10}, {"art", 25},
};
qsort(records, 5, sizeof *records, by_minutes_desc);
for (size_t i = 0; i < 5; ++i) {
printf("%s %d\n", records[i].topic, records[i].minutes);
}
return 0;
}Hint 1: the idea
Descending order reverses the relationship, not the values. Swap the two comparisons from compare_ints, so a larger left value gives a negative result and comes first.
Hint 2: a first step
Write a comparator that handles minutes only, and run: everything is right except that the two 25s and the two 10s may come out in either order. Then decide what to return when the minutes are equal; the topics are strings.
Show one solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char topic[24]; int minutes; } Record;
static int by_minutes_desc(const void *left, const void *right) {
const Record *a = left;
const Record *b = right;
int minutes = (a->minutes < b->minutes) - (a->minutes > b->minutes);
if (minutes != 0) { return minutes; }
return strcmp(a->topic, b->topic);
}
int main(void) {
Record records[5] = {
{"reading", 10}, {"reading", 25}, {"coding", 40}, {"math", 10}, {"art", 25},
};
qsort(records, 5, sizeof *records, by_minutes_desc);
for (size_t i = 0; i < 5; ++i) {
printf("%s %d\n", records[i].topic, records[i].minutes);
}
return 0;
}coding 40
art 25
reading 25
math 10
reading 10Two pairs tie on minutes, and the topic key decides both, so this output is the same with every C library. Writing return -strcmp(...) for a descending text key would also be safe, because strcmp results are small, but negating an arbitrary int is not: -INT_MIN overflows. The checkpoint next walks the sorted array and prints one summary line per group.
Completion is saved in this browser only. It does not measure mastery.