Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access structure fields by name at run time?

Tags:

c

struct

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!

like image 537
drigoSkalWalker Avatar asked Mar 25 '10 13:03

drigoSkalWalker


1 Answers

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;

}
like image 62
Naveen Avatar answered Oct 26 '22 22:10

Naveen