简体   繁体   English

C: 指向 char[] 类型结构成员的空指针

[英]C: void pointer to struct member of type char[]

I have this class我有这堂课

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

and then this array:然后这个数组:

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

I then want to write a function that I can pass to qsort ;然后我想编写一个可以传递给qsort的函数; a function like this:像这样的函数:

int compare_name(const void *a, const void *b);

Normally, when for example having an array of string like this通常,例如当有这样的字符串数组时

char names[5][10] = { "xxx", "uuu", "ccc", "aaa", "bbb" };

I would be able to work with the const void * a and const void *b like this:我将能够像这样使用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;

But how do I write the same method, that is how do I tell C that the void pointer is referring to the field name of the struct person if I want to sort the array according to alphabetical order?但是我如何编写相同的方法,即如果我想根据字母顺序对数组进行排序,我如何告诉 C 空指针指的是struct person的字段name

Eventually, I would need to be able to call qsort like this:最终,我需要能够像这样调用qsort

int npeople = sizeof(class) / sizeof(struct student);
qsort(people, npeople, sizeof(struct person), compare_name);

But as said, I am not able to turn const void *a into the needed value ( person->name ) like I did with *( char*)a when simply working with an array of strings.但如前所述,我无法像使用*( char*)a简单地处理字符串数组时将const void *a转换为所需的值( person->name )。

Many thanks in advance for your help!非常感谢您的帮助!

I have this class我有这堂课

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

and then this array:然后这个数组:

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

There are many typos in your code as for example struct person and struct student are different type specifiers.您的代码中有许多拼写错误,例如struct personstruct student是不同的类型说明符。 And there are no classes in C opposite to C++.并且 C 中没有与 C++ 相对的类。

Nevertheless the comparison function can look the following way尽管如此,比较函数可以如下所示

#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 );
} 

Also pay attention to that increment operations like this a++, b++ are not defined for pointers of the type c/v void * though some compilers can have their own language extensions that contradict the C Standard..还要注意像a++, b++这样a++, b++增量操作没有为c/v void *类型的指针定义,尽管一些编译器可以有自己的与 C 标准相矛盾的语言扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM