Thread overview | |||||
---|---|---|---|---|---|
|
October 10, 2005 Question about structs | ||||
---|---|---|---|---|
| ||||
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? |
October 10, 2005 Re: Question about structs | ||||
---|---|---|---|---|
| ||||
Posted in reply to KUV | "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). |
October 13, 2005 Re: Question about structs | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jarrett Billingsley | 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
|
Copyright © 1999-2021 by the D Language Foundation