How to access `struct 'elements according to string value?

I would like to access the member inside the structure using the string value:

struct hello_world { char rate; char ssid; }; 

There is varibale let say

 char *string="ssid"; 

I would like to use the value of this string to refer to the ssid member in the hello_world structure. Is it possible?

+4
source share
3 answers

No, it is not.

You will need a (long) if-else statement that does this. How:

 struct hello_world hw; char *string="ssid"; if( 0 == strcmp( "ssid", string ) ) { // use hw.ssid } else if ... 
+5
source

Instead of using a string, you better use an enumeration with all possible cases.

 typedef enum { FIELD_SSID, FIELD_RATE, } field_t field_t string; 

and then use the switch

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

This method is faster than string comparison.

If you use only one field OR another, you can use a union instead of a structure.

+2
source

Define a function, such as a shell, to convey the part you need.

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

But the language itself does not provide you with anything like this.

0
source

All Articles