In column 15.3, the author introduced how to generate text randomly from an input document. The author also gave the source code.
qsort(word, nword, sizeof(word[0]), sortcmp);
int sortcmp(char **p, char **q)
{ return wordncmp(*p, *q);
}
I've been confused by the above lines in the source code. The last argument of qsort is:
int comparator ( const void * elem1, const void * elem2 ).
But the definition of sortcmp is different. Actually, the source code cannot compiled in my VS2010.
It seems this code was originally compiled with a more forgiving (or less standard-compliant) compiler. The idea seems to be that the canonical void *
arguments of the comparator function are interpreted as char **
so that wordncmp()
, which is an implementation of lexicographical comparison of up to length n
, can be applied to them.
Declaring the function as expected (i.e. taking two const void *
arguments) and making the type casts explicit appears to solve the problem (tested with GCC 4.7.0):
int sortcmp(const void *p, const void *q) {
return wordncmp(*(const char **)p, *(const char **)q);
}
I also had to modify the declaration of the wordncmp()
function:
int wordncmp(const char *p, const char* q)
{
/*.. Definition unchanged.. */
}