Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access struct member using a user variable

Tags:

c

struct

Let's asume I have a struct as follows:

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

and the user gives an argument which struct member the program should read. ./program age

int main(int argc, char **argv) {
    int i;
    i = person.argv[1];
    printf("%i\n", i);
}

this is obviously not possible in this way. Is there a way to read a struct member without typing the exact member name in code? The only way I could think of is to compare the given string to a string named after each struct member.

like image 346
Hans-Helge Avatar asked Jan 23 '26 06:01

Hans-Helge


2 Answers

C does not support run-time reflection in any way that would make that easy to get to work. I suspect the best you can do is to write a code-generator that writes the string-to-struct member selection function.

like image 165
Vatine Avatar answered Jan 24 '26 22:01

Vatine


The most efficient way to code this, both in terms of typing and run-time performance, is probably to use gperf.

Basically, you type the list of names you want, and what you want that to map to (array index, variable pointer, whatever) and it will generate C code to do that for you.

The only problem is that you have to learn how to use it first.

Here's an example from some real-world code: conf.c confitems.gperf

Note that the gperf file maps a string to a C macro so the programmer can put whatever they like inside that macro, and even use it for different purposes in different places. The C file then includes the generated code, and call the generated function confitems_get to do the mapping: string in, macro contents out.

like image 35
ams Avatar answered Jan 24 '26 23:01

ams