qsort没有排序字符串数组
我尝试使用qsort对字符串数组进行排序。 这是我的数组的内容:
{"a","orange","apple","mobile","car"}
这就是我使用qsort的方式:
int myCompare (const void * a, const void * b ) { const char *pa = (const char*)a; const char *pb = (const char*)b; return strcmp(pa,pb); } int stringLen = sizeof(input)/sizeof(char *); qsort(input, stringLen, sizeof (char*), myCompare);
但是,当我打印数组时,没有任何改变。 这有什么不对吗?
我已将myComparefunction更改为Mitch Wheat之前发布的内容,并且该function正常。 这是一个例子:
#include #include #include int myCompare (const void * a, const void * b ) { const char *pa = *(const char**)a; const char *pb = *(const char**)b; return strcmp(pa,pb); } int main() { int i; const char *input[] = {"a","orange","apple","mobile","car"}; int stringLen = sizeof(input) / sizeof(char *); qsort(input, stringLen, sizeof(char *), myCompare); for (i=0; i
这将返回:
0: a 1: apple 2: car 3: mobile 4: orange
qsort(input, stringLen, sizeof (char*), myCompare)
调用myCompare
来比较排序的字符串。
myCompare
获取指向比较值的指针 。 在我们的例子中,我们得到指向字符串的指针( const char**
)。 所以我们应该比较*(const char**)a
和*(const char**)b
,它们是由a
和b
指向的字符串。
开始调试:
int myCompare (const void * a, const void * b ) { const char *pa = (const char*)a; const char *pb = (const char*)b; printf("Comparing %s vs. %s for result %d\n", pa, pb, strcmp(pa,pb)); return strcmp(pa,pb); }
我想在那之后不久,你会发现问题所在。 🙂