【问题标题】:C: void pointer to struct member of type char[]C:指向 char[] 类型的结构成员的 void 指针
【发布时间】: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 * aconst 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


【解决方案1】:

我有这门课

 struct person {
     char name[100];
     int age }; 

然后是这个数组:

struct student people[] = { {"bill", 30}, {"john", 20}, {"bob", 11} };

您的代码中有许多拼写错误,例如 struct personstruct student 是不同的类型说明符。而且C中没有与C++相反的类。

不过比较函数可以如下所示

#include <string.h>

//...

int compare_name( const void *a, const void *b )
{
    const struct person *p1 = a;
    const struct person *p2 = b;

    return strcmp( p1->name, p2->name );
} 

还要注意像 a++, b++ 这样的递增操作不是为 c/v void * 类型的指针定义的,尽管一些编译器可能有自己的语言扩展,这些扩展与 C 标准相矛盾..

【讨论】:

  • 是的,抱歉,struct student people[] 应该是 struct person people[]。我明白了,这是有道理的,谢谢!
  • 另外,我不知道“对于 c/v void * 类型的指针没有定义像这样的 a++、b++ 这样的增量操作”,这也解释了为什么我以前的代码是效果不太好。
猜你喜欢
  • 2021-08-11
  • 1970-01-01
  • 2023-03-12
  • 2016-03-21
  • 2018-03-24
  • 2019-03-18
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
相关资源
最近更新 更多