lvella lvella - 3 months ago 17
C Question

struct similarity in C

Consider the two

struct
s below:

struct A {
double x[3];
double y[3];
int z[3];

struct A *a;
int b;
struct A *c;
unsigned d[10];
};

struct B {
double x[3];
double y[3];
int z[3];
};


Notice that
struct B
is a strict subset of
struct A
. Now, I want to copy the members
.x
,
.y
and
.z
from an instance of
struct A
to an instance of
struct B
. My question is: according to the standards, is it valid to do:

struct A s_a = ...;
struct B s_b;
memcpy(&s_b, &s_a, sizeof s_b);


I.e. is it guaranteed that the paddings for the members, in their sequence of appearance, will be the same, so that I can "partially"
memcpy
struct A
to
struct B
?

M.M M.M
Answer

It is not guaranteed that struct A's layout starts off the same as struct B's layout.

However, if and only if they were both members of a union:

union X
{
    struct A a; 
    struct B b;
};

then it is guaranteed that the common initial sequence has the same layout.

I've never heard of any compiler that would lay out a struct differently if it detected that the struct were a member of a union, so in practice you should be safe!