我尝试使用 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);
但是,当我打印数组时,没有任何变化。这有什么问题吗?
我已将您的 myCompare 函数更改为 Mitch Wheat 之前发布的函数,并且工作正常。这是例子:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
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<stringLen; ++i)
printf("%d: %s\n", i, input[i]);
}
这将返回:
0: a
1: apple
2: car
3: mobile
4: orange
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)