Accessing child variables through higher level structures

后端 未结 8 1766
孤街浪徒
孤街浪徒 2020-12-09 17:41

If I have these structures:

typedef struct { int x; } foo;
typedef struct { foo f; } bar;

Normally you would access x through

8条回答
  •  醉梦人生
    2020-12-09 17:55

    Since the C standard guarantees that there isn't padding before the first member of a struct, there isn't padding before the foo in bar, and there isn't padding before the x in foo. So, a raw memory access to the start of bar will access bar::foo::x.

    You could do something like this:

    #include 
    #include 
    
    typedef struct _foo
    {
        int x;
    } foo;
    
    typedef struct _bar
    {
        foo f;
    } bar;
    
    int main()
    {
        bar b;
        int val = 10;
    
        // Setting the value:
        memcpy(&b, &val, sizeof(int));
        printf("%d\n", b.f.x);
    
        b.f.x = 100;
    
    
        // Reading the value:
        memcpy(&val, &b, sizeof(int));
        printf("%d\n", val);
        return 0;
    }
    

    As others have noted, C++ offers a more elegant way of doing this through inheritance.

提交回复
热议问题