使用用户变量访问结构成员 [英] access struct member using a user variable
问题描述
假设我有一个结构如下:
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.
推荐答案
最有效的编码方式,无论是在输入还是运行时性能方面,可能是使用 gperf.
The most efficient way to code this, both in terms of typing and run-time performance, is probably to use gperf.
基本上,你输入你想要的名字列表,以及你想要映射到什么(数组索引、变量指针等等),它会生成 C 代码来为你做这些.
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.
以下是一些真实代码的示例:conf.cconfitems.gperf/a>
Here's an example from some real-world code: conf.c confitems.gperf
请注意,gperf 文件将字符串映射到 C 宏,因此程序员可以将他们喜欢的任何内容放入该宏中,甚至可以在不同的地方将其用于不同的目的.然后 C 文件包含生成的代码,并调用生成的函数 confitems_get
进行映射:字符串输入,宏内容输出.
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.
这篇关于使用用户变量访问结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!