我正在尝试编写一个函数,在其中对 wptrs 内部的指针进行排序,wptrs 是指向另一个数组中字符串的指针数组。我挑战自己不要在这个练习中使用 string.h,因为我想了解排序算法如何在 C 中工作。但是,我正在使用 qsort()
,但我正在尝试编写一个名为 mycharptrcompare()
的比较函数。
我研究了 strcmp()
的工作原理,并尝试使用 mycharptrcompare()
来模仿它。但是,我注意到 strcmp()
需要一个 char* ,而 mycharptrcompare()
函数需要一个 char** 。我编写了一个名为 dumpwptrs
的方法来显示内容以及它们在 wptrs
中的组织方式。到目前为止,我有以下代码:
更新:
我也尝试过:
int mycharptrcompare(const void *a, const void *b)
{
//Need to convert a void * to a more specific type to dereference
const char *aPtr = a;
const char *bPtr = b;
const char **pa = &aPtr;
const char **pb = &bPtr;
while (*pa && *pa == *pb) {
pa++;
pb++;
}
return *pa - *pb;
}
我得到的输出是:
(空)
跳跃
世界
是
狗
蓝色
这仍然是不正确的,因为我的列表应该按字母顺序排序,并且第一个输入(单词“hello”)尚未被读入。
最佳答案
仅供引用,这里是 qsort()
的使用示例。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b)
{
const char **pa = a;
const char **pb = b;
return strcmp(*pa, *pb);
}
int main(void)
{
char *wptrs[] = { "hello", "jumps", "world", "is", "dog", "blue" };
size_t len = sizeof wptrs / sizeof wptrs[0];
qsort(wptrs, len, sizeof wptrs[0], cmp);
for(size_t i = 0; i < len; i++) {
printf("%s\n", wptrs[i]);
}
return 0;
}
程序输出:
blue dog hello is jumps world
关于c - 如何按字母顺序对指针数组进行排序,然后使用 qsort?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56726504/