Question about memory layout

Do these two structures have the same memory layout? (C ++)

struct A
{
   int x;
   char y;
   double z;
};

struct B
{
   A a;
};

Next, can I access the elements x, y, z if I manually transfer the object of this object to A?

struct C
{
   A a;
   int b;
};

Thanks in advance.

EDIT:

What if they were classesinstead structs?

+3
source share
4 answers

Yes and yes. The latter is commonly used to emulate OO inheritance in C.

+7
source

You can verify this yourself by checking the field offsets relative to the start of each instance.

A aObj;
B bObj;
C cObj;

int xOffset1 = &aObj.x - &aObj;
int xOffset2 = &bObj.a.x - &bObj;

ASSERT(xOffset1 == xOffset2);

etc.

+4
source

$9.2/16- " ( 9) , ( ) (3.9)."

, ""

+2
source

Yes, that will work. Depending on the packaging settings of the compiler structure, it may not work with members other than the first one.

+1
source

Source: https://habr.com/ru/post/1769525/


All Articles