如何在运行时按名称访问结构字段?

dri*_*ker 4 c struct

C faqs以某种方式解释它,这里是链接.

但我无法理解,有人能为我解释一下吗?或者给我另一种方式?

非常感谢!

Nav*_*een 7

我认为这个例子清楚地说明了答案:

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;

}
Run Code Online (Sandbox Code Playgroud)