union/struct alignment safety

S

Sean Hamilton

struct a { uint8_t b, c, d, e; };
union b { uint8_t f[16]; struct a g[4]; };

Is it guaranteed that b.f and b.g will have the same address and size?
Is a struct with only one type of member like that equivalent to an
array with regard to alignment and padding?

Thanks in advance,
 
A

Andrey Tarasevich

Sean said:
struct a { uint8_t b, c, d, e; };
union b { uint8_t f[16]; struct a g[4]; };

Is it guaranteed that b.f and b.g will have the same address and size?

The same address is guaranteed. The size is not guaranteed to be the
same. However, it "should" be the same in any reasonable practical
implementation.
Is a struct with only one type of member like that equivalent to an
array with regard to alignment and padding?

No, he language make no such guarantee. And again, what will happen in
practice depends on implementation. Normally one should expect the
equivalence of memory layouts for array and struct to hold, unless one
takes specific steps to break that equivalence (like adjust struct field
alignment by implementation-specific means).
 
R

Richard Damon

struct a { uint8_t b, c, d, e; };
union b { uint8_t f[16]; struct a g[4]; };

Is it guaranteed that b.f and b.g will have the same address and size?
Is a struct with only one type of member like that equivalent to an
array with regard to alignment and padding?

Thanks in advance,

for union, the address of each member will be the same, that of the
union, no padding before the member is allowed.

The size may not be the same. Structs may have padding, and the compiler
may decide that it is helpful for all structs to have a certain minimal
alignment, which if it was larger than 4, might cause sizeof(struct a)
to be > 4. This is particularly likely on a word addresses machine,
where pointers to individual bytes requires a longer pointer to add byte
offsets, as a pointer to struct needs to have its format defined
independent of the detail of the contents of the struct.

So a Word Addressed machine with 64 bit words, would likely added 4
bytes of padding to struct a.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top