qsort按字典顺序对c中的字符串进行排序
qsort to lexigraphically sort strings in c
我想使用 stdlib
函数 qsort
对字符串数组进行排序。
我有填充数组:char *words[MAX_WORDS];
和一个比较函数:
int compare_words(const void *p, const void *q) {
printf("%s\n", (const char*)p); // For debugging
return strcmp((const char*)p, (const char*)q);
}
使用 qsort
调用:qsort(words, i, sizeof(char*), compare_words);
我可以从我插入到 compare_words
函数中的输出中看出 qsort 没有将正确的参数传递给 compare_words
。 (它打印垃圾)。关于为什么它没有获得正确的字符指针有什么想法吗?
qsort
将指针传递给您的数组元素,因此您实际上得到的是 const char **
而不是 const char*
.
特别是,将这些指针打印为 const char*
会将输入数组的一部分打印为文本,因此很明显你得到的是垃圾。
我想使用 stdlib
函数 qsort
对字符串数组进行排序。
我有填充数组:char *words[MAX_WORDS];
和一个比较函数:
int compare_words(const void *p, const void *q) {
printf("%s\n", (const char*)p); // For debugging
return strcmp((const char*)p, (const char*)q);
}
使用 qsort
调用:qsort(words, i, sizeof(char*), compare_words);
我可以从我插入到 compare_words
函数中的输出中看出 qsort 没有将正确的参数传递给 compare_words
。 (它打印垃圾)。关于为什么它没有获得正确的字符指针有什么想法吗?
qsort
将指针传递给您的数组元素,因此您实际上得到的是 const char **
而不是 const char*
.
特别是,将这些指针打印为 const char*
会将输入数组的一部分打印为文本,因此很明显你得到的是垃圾。