我试图弄清楚如何将qsort与字符串数组一起使用。我的代码看起来像这样。
char words[500][256];
int numOfWords; // this is calculated above
int sortWordList() {
int length = sizeof(words) / sizeof(char *);
qsort(words, length, sizeof(char*), compare);
}
int compare (const void * a, const void * b ) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;
return strcmp(pa,pb);
}
然而,我得到一个"访问冲突读取位置0x ### .."我每次都不知道什么是错的。有谁能发现我的问题?
编辑:感谢您的精彩帮助。你们总是最好的。答案 0 :(得分:1)
您没有正确地将const void *
投射到const char *
,为此,请改为使用:
const char *pa = (const char *)a;
const char *pb = (const char *)b;
当您在compare()
中使用时, Plus sortWordList()
应高于sortWordList()
。