Context
I am trying to learn C and came across an example of using qsort to sort an array of strings.
Questions:
I am struggling to understand the following:
- Why these two return statements are different?
- Why do we need to cast the void pointer to (char **) instead of just (char *).
int CompareWords(const void *a, const void *b) {
char **str1 = (char **)(a);
char **str2 = (char **)(b);
char *c1 = (char *)a;
char *c2 = (char *)b;
return strcmp(c1, c2);
// return strcmp(*str1, *str2);
}
The casts themselves are not needed.
The casts serve to lose the
const-ness.Like code can be made without casts.
Why these two return statements are different?
They serve different goals. The correct one to use depends on how
qsort()is used. Likely thereturn strcmp(*str1, *str2)is correct as the compare function passed toqsort()expects the addresses of the objects to compare.