Hi everyone,
I've managed to write a working program in response to Exercise 6.4 in K&R (2nd Ed, p. 143) ('Write a program that prints the distinct words in its input sorted into decreasing order of frequency of occurrence. Precede each word by its count.') but only after much difficulty in getting qsort to work with my comparison function. Here's the code with the irrelevant bits cut out:
Code:
typedef struct wordc {
char *word;
unsigned int count;
} Word;
...
int treecount(Treeptr); /* Treeptr is a pointer to a node in a binary tree */
int main (void)
{
unsigned int nwords;
...
nwords = treecount(root); /* count no. of words in binary tree */
...
Word *freqlist[nwords-1];
...
qsort(freqlist, nwords, sizeof(Word *), wcountcmp);
...
return 0;
}
int wcountcmp (const void *w1, const void *w2)
{
Word *nw1 = *(Word * const *)w1;
Word *nw2 = *(Word * const *)w2;
if (nw1->count == nw2->count) {
return 0;
}
return nw1->count < nw2->count ? -1 : 1;
}
The program worked after modifying wcountcmp() based on information from this page: http://c-faq.com/lib/qsort2.html.
However, I still don't understand the method of casting i.e. of the form:
struct mystruct *sp1 = *(struct mystruct * const *)p1;
On the right side, what do the asterisks after 'mystruct' and 'const' do? And what about the asterisk outside the brackets i.e. before (struct ... ?
Any help much appreciated.