gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:34:23 24 4
gpt4 key购买 nike

我试图弄清楚如何将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com