简体   繁体   English

如何根据字符串的值访问`struct'的成员?

[英]How to access members of a `struct' according to a value of a string?

I would like to access a member within a struct by using the value of a string: 我想通过使用字符串的值来访问结构中的成员:

struct hello_world
{
           char rate;
           char ssid;
};

There is a varibale let's say 有一个varibale让我们说

char *string="ssid";

I would like to use the value of this string to refer to the ssid member within the hello_world struct. 我想使用此字符串的值来引用hello_world结构中的ssid成员。 Is this possible? 这可能吗?

Nope, it's not. 不,不是。

You need a (long) if-else statement, that will do this. 你需要一个(长) if-else语句,这样做。 Like: 喜欢:

struct hello_world hw;
char *string="ssid";

if( 0 == strcmp( "ssid", string ) )
{
     // use hw.ssid
}
else if ...

Instead of using a string, you are better off using an enum with all the possible cases. 您最好使用包含所有可能情况的枚举,而不是使用字符串。

typedef enum {
    FIELD_SSID,
    FIELD_RATE,
} field_t

field_t string;

and then use a switch 然后使用开关

switch (string) {
    case FIELD_SSID:
        //use ssid
        break;
    case FIELD_RATE:
        //use rate
        break;
}

This method is way faster than comparing strings. 此方法比比较字符串更快。

If you only use one field OR the other, you could use a union instead of a struct. 如果您只使用一个字段另一个字段,则可以使用union而不是struct。

Define a function, like a wrapper to pass the member back you want. 定义一个函数,就像一个包装器,将你想要的成员传递回去。

char GiveMember(struct hello_world, char* member){ }

But the language itself does not provide you with anything like this. 但语言本身并没有为你提供这样的东西。

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

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