www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Question about structs

reply KUV <KUV_member pathlink.com> writes:
struct NodeLink {
char c;
int node;
}
...
printf("%i\n", NodeLink.sizeof);

This code prints 8, but summary size of fields is 5. Is it normal?
Oct 10 2005
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"KUV" <KUV_member pathlink.com> wrote in message 
news:dieoqt$15r2$1 digitaldaemon.com...
 struct NodeLink {
 char c;
 int node;
 }
 ...
 printf("%i\n", NodeLink.sizeof);

 This code prints 8, but summary size of fields is 5. Is it normal?
This is because of member alignment, for optimization reasons (it's faster for the processor to access memory on 32-bit boundaries). If you put an align(1) in front of the struct, like so: align(1) struct NodeLink { char c; int node; } The NodeLink.sizeof will be 5. Of course, if the layout of the struct doesn't have to be so strict, it'd be recommended to use the default alignment for performance reasons; but if this is being used to paint a data structure over an arbitrary chunk of memory, you'd need the align(1).
Oct 10 2005
parent Oskar Linde <olREM OVEnada.kth.se> writes:
Jarrett Billingsley wrote:


 This code prints 8, but summary size of fields is 5. Is it normal?
This is because of member alignment, for optimization reasons (it's faster for the processor to access memory on 32-bit boundaries). If you put an align(1) in front of the struct, like so: align(1) struct NodeLink { char c; int node; } The NodeLink.sizeof will be 5. Of course, if the layout of the struct doesn't have to be so strict, it'd be recommended to use the default alignment for performance reasons; but if this is being used to paint a data structure over an arbitrary chunk of memory, you'd need the align(1).
For this reason, it is also generally recommended (when possible) to put the larger fields before the smaller in the struct.. struct a { int a; short b; short c; } struct b { short b; int a; short c; } void main() { printf("%d %d\n",a.sizeof,b.sizeof); } should generally print 8 12. /Oskar
Oct 13 2005