If I have these structures:
typedef struct { int x; } foo;
typedef struct { foo f; } bar;
Normally you would access x
through
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.