c - qsort 一个字符串数组,比较

标签 c arrays string qsort

我试图弄清楚如何将 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###..”,但我不知道出了什么问题。谁能发现我的问题吗?

编辑:感谢您的大力帮助。你们永远是最棒的。

最佳答案

您没有正确地将 const void * 转换为 const char *,为此,请改用:

const char *pa = (const char *)a;
const char *pb = (const char *)b;

加上 compare() 应该位于 sortWordList() 之上,因为您在 sortWordList() 中使用它。

关于c - qsort 一个字符串数组,比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23302424/

相关文章:

java - 星号字符串,屏蔽密码

解决多项式问题的C程序

c - 用 strtok 分隔字符串

c - 在 cygwin 中与 gcc 动态链接时 undefined reference

c++ - 在二维数组中查找最大值的快速算法

java - 将长字符串压缩为较短的字符串,这是使用 Java 所独有的

c - linux下如何创建一个带超时的文件锁

python - 复制numpy数组的速度

C# 手动填充 double[][]

python - 多字符串替换Python