This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

sizeof struct

I have a struct with 2 members of type double and 1 member of type long.

The sizeof() function returns 24. Normaly it should be 20(2*8bytes for the doubles and 4 bytes for the long).

When I add a another member of type long sizeof() returns 32.

Another struct with 3 longs returns 12 with sizeof().

I suppose it has something to do with allignment and optimalisation? How can I avoid this.

Luc Vercruysse

Parents
  • A struct always gets its size adjusted to be n times the member with the highest alignment requirement.

    If you have an 8-byte double in the struct, then the struct must be n*8 bytes large, so your first example will need four bytes of padding.

    If you place the two long values directly after each other, then the modified struct should stay at 24 bytes. If you have one or more double between the two long, then the compiler needs two padding areas of four bytes each, resulting in a total size of 32 byte.

Reply
  • A struct always gets its size adjusted to be n times the member with the highest alignment requirement.

    If you have an 8-byte double in the struct, then the struct must be n*8 bytes large, so your first example will need four bytes of padding.

    If you place the two long values directly after each other, then the modified struct should stay at 24 bytes. If you have one or more double between the two long, then the compiler needs two padding areas of four bytes each, resulting in a total size of 32 byte.

Children