【发布时间】:2021-12-01 05:43:25
【问题描述】:
我有这门课
struct person {
char name[100];
int age
};
然后是这个数组:
struct student people[] = { {"bill", 30}, {"john", 20}, {"bob", 11} };
然后我想写一个可以传递给qsort的函数;像这样的函数:
int compare_name(const void *a, const void *b);
通常,例如,当有这样的字符串数组时
char names[5][10] = { "xxx", "uuu", "ccc", "aaa", "bbb" };
我可以像这样使用 const void * a 和const void *b :
int compare_name(const void *a, const void *b) {
for (; *( char*)a == *(char *)b; a++, b++)
if (*(char *)a == '\0') return 0;
return *(char *)a - *(char *)b;
但是我如何编写相同的方法,即如果我想按字母顺序对数组进行排序,我如何告诉 C void 指针指向 struct person 的字段 name?
最终,我需要能够像这样调用qsort:
int npeople = sizeof(class) / sizeof(struct student);
qsort(people, npeople, sizeof(struct person), compare_name);
但如前所述,我无法将 const void *a 转换为所需的值 (person->name),就像我在处理字符串数组时对 *( char*)a 所做的那样。
非常感谢您的帮助!
【问题讨论】:
-
struct person 和 struct student 是不同的结构。
-
你没有;你有指向你想要比较的东西的指针(
structs),比较函数知道 如何 进行比较(在这种情况下,通过比较name的字段那些structs)。 -
是的,对不起,struct student people[] 应该是 struct person people[];如果有人可以编辑它,那就太好了!
标签: c struct string-comparison void-pointers qsort