digitalmars.D - Question about structs
- KUV (7/7) Oct 10 2005 struct NodeLink {
- Jarrett Billingsley (14/21) Oct 10 2005 This is because of member alignment, for optimization reasons (it's fast...
- Oskar Linde (18/34) Oct 13 2005 For this reason, it is also generally recommended (when possible) to put...
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
"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
Jarrett Billingsley wrote: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. /OskarThis 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 13 2005