如何在运行时按名称访问结构字段? [英] How can I access structure fields by name at run time?
本文介绍了如何在运行时按名称访问结构字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C 常见问题解答以某种方式解释它,这里是链接.>
但是我看不懂,谁能帮我解释一下?或者给我另一种方式?
非常感谢!
解决方案
我认为这个例子已经说明了答案:
结构测试{国际b;一个;};int main(){测试 t;测试* structp = &t;//在结构中找到'a'的字节偏移量int offsetf = offsetof(test, a);//使用指针算法设置'a'的值*(int *)((char *)structp + offsetf) = 5;返回0;}
The C faqs explain it in a way, here is the link.
But I can't understand it, Somebody can explain it for me? Or give me another way?
Thanks so much!
解决方案
I think this example makes the answer clear:
struct test
{
int b;
int a;
};
int main()
{
test t;
test* structp = &t;
//Find the byte offset of 'a' within the structure
int offsetf = offsetof(test, a);
//Set the value of 'a' using pointer arithmetic
*(int *)((char *)structp + offsetf) = 5;
return 0;
}
这篇关于如何在运行时按名称访问结构字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文