开发者

how to implement qsort in C

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 vo开发者_开发问答id * 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);


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜