I am trying to understand what is going on in the first few lines of this comparator function stringAsInt(const void *pLeft, const void *pRight)
- So the parameters are constant pointers for something. Then in the next two lines we are casting the void to
(const char**)
Why is it being cast to a pointer of a pointer? Also, what exactly is going on in those two lines? - When calling
qsort()
in themain()
function, why are there no parameters being passed tostringAsInt()
? How doesstringAsInt()
know whatpLeft
andpRight
are? - Why is
a
being setup as a pointer of a pointer? Wouldn't a standard array suffice?
-
int stringAsInt(const void *pLeft, const void *pRight) {
const char *left = *(const char**)pLeft;
const char *right = *(const char**)pRight;
int leftLen = (int)strlen(left);
int rightLen = (int)strlen(right);
if (leftLen != rightLen) {
return leftLen - rightLen;
} else {
return strcmp(left, right);
}
}
int main() {
int n;
scanf("%d", &n);
char buffer[1000000 + 1];
char **a = malloc(sizeof(char*) * (size_t)n);
for (int i = 0; i < n; i++) {
scanf("%1000000s", buffer);
a[i] = malloc(sizeof(char) * (strlen(buffer) + 1));
strcpy(a[i], buffer);
}
qsort(a, (size_t)n, sizeof(a[0]), stringAsInt);
for (int i = 0; i < n; i++) {
printf("%s\n", a[i]);
free(a[i]);
}
free(a);
return 0;
}
It's type erasure in C. qsort does not know what type do array elements have, it only knows their sizes and passes individual elements to the comparator as type-erased pointers to void, expecting comparator to cast the pointers to the needed type. That is exactly what happens in these two lines. Array of strings is simply organized as array of pointers to char (a traditional C idiom for character string). Each element of array is a pointer to character (actually, to the first one in a contigous sequence of characters). qsort passes type-erased pointers to those, comparator downcasts them back to the concrete type.
It is a pointer to function. qsort's last argument is a function pointer. It then calls this function to compare individual pairs of elements, each time providing values for pLeft and pRight.
Probably, if you know for sure that your file is not large. If it consists of milliards of strings, the program would be likely to crash due to the 2nd level domain of this site's URI, so they decided to put the whole array on heap.