tags:

views:

221

answers:

1

I need to implement qsort in C and sort in reverse lexicographical order. I'm confused on how to create and call the comparison function. This is what I have so far..

qsort (strArr, numLines, sizeof(char*) , sort);

int sort(const void * str1, const void * str2) {
 return (-1) * strcasecmp((char*) str1, (char*) str2);
};

Eclipse is telling me "'sort' undeclared (first use in this function)" on the qsort line, but I fear that's not my only problem. Any advice?

Thanks, Hristo

Revision... this is what my array looks like:

char **strArr = malloc(numLines * sizeof(char*));
fgets(output, 256, sourceFile);
strArr[i] = malloc(((int) strlen(output) + 1) * sizeof(char));
strcpy(strArr[i],output);
+6  A: 

you would need to declare sort before using it:

int sort(const void * str1, const void * str2);

then the comparison might be:

return strcasecmp(*(char * const *)str2, *(char * const *)str1);

As @Chris Jester-Young points out you can swap the args to reverse the comparison.

the pointers have to be dereferenced...

right! I forgot to put it in the header. Thanks
Hristo
@Robert: The pointers have to be dereferenced since `qsort` calls the comparison function with pointers to the array elements, so in this case pointers to `char*`.
sth
`qsort` calls the comparison function with pointers to two elements of the array being sorted. The elements in this case are `char *`, so the comparison function is being called with pointers to `char *` - so `char **` is right.
caf
doh! caf's comment straightened me out. You (gbacon and sth) are correct. Apparently I'm up past my bedtime.
Robert
take a look at my array above. I'm not sure if I'm following you all with the dereference or not argument. Also, the sort is not sorting properly. Any ideas as to why?
Hristo
@Hristo: Basically you should ignore my first comment. Secondly, did you update the casts in the strcasecmp call?
Robert
this is what my return is: return strcasecmp((char const*) str2, (char const *) str1);
Hristo
Use return strcasecmp(\*(const char\*\*)str2, \*(const char \*\*)str1);
Robert
Thanks! That works like a charm.
Hristo
+1 to jxac, gbacon, sth, and caf.
Robert
As to eliminate possible future confusion, I've deleted my erroneous comment which stated that the dereference was not needed. (It clearly is needed).
Robert