[英]how to implement qsort in C
I need to implement qsort in C and sort in reverse lexicographical order. 我需要在C中实现qsort并按相反的字典顺序排序。 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. Eclipse在qsort行上告诉我“未声明'sort'(此功能的首次使用)”,但我担心这不是我唯一的问题。 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: 您需要在使用它之前声明sort:
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. 正如@Chris Jester-Young指出的那样,您可以交换args来反转比较。
the pointers have to be dereferenced... 指针必须被取消引用...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.