Organization of Structs

P

pradeep

Hello friends,

If we have a struct definition like this

typedef struct s {
char a;
int b;
char c;
} _s;

where because of alignment effects the layout given results in memory
inefficiency, do we need to manually arrange things (char then char
then int) or will a good optimizing compiler automatically reorder the
fields in the struct?

Also if we do arrange it as char then char then int, the first dword
in the struct will have two char bytes and two padding bytes. How will
the compiler organize the space and why? Will it be
padding - padding - char - char
or padding - char - padding - char
or char - char - padding - padding
etc.?

Thanks.
 
I

Ian Collins

pradeep said:
Hello friends,

If we have a struct definition like this

typedef struct s {
char a;
int b;
char c;
} _s;

where because of alignment effects the layout given results in memory
inefficiency, do we need to manually arrange things (char then char
then int) or will a good optimizing compiler automatically reorder the
fields in the struct?
No, the order is fixed.
Also if we do arrange it as char then char then int, the first dword
in the struct will have two char bytes and two padding bytes. How will
the compiler organize the space and why? Will it be

That is entirely up to the compiler.
 
B

Ben Bacarisse

pradeep said:
If we have a struct definition like this

typedef struct s {
char a;
int b;
char c;
} _s;

where because of alignment effects the layout given results in memory
inefficiency, do we need to manually arrange things (char then char
then int) or will a good optimizing compiler automatically reorder the
fields in the struct?

The compiler can't re-order the struct.
Also if we do arrange it as char then char then int, the first dword
in the struct will have two char bytes and two padding bytes. How will
the compiler organize the space and why? Will it be
padding - padding - char - char
or padding - char - padding - char
or char - char - padding - padding

The only options are ones that have no padding at the start. That
leaves three possibilities. I'd lay odds on it using char, char,
padding, but you can't assume that it will do so.

As to why, the usually strategy is that the compiler puts a field at
the first offset that will incur no access penalty.
 

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

Similar Threads

Array of structs function pointer 10
bitfield organization 7
packing and structs 5
packed structs 35
structs 12
Practical packing for structs of bytes 12
Copy array of structs in one go 24
Initialization of Structs - Typedefs 6

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top