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
  • Normaly it should be 20

    Just to make this crystal clear: this statement expresses a fundamentally incorrect belief. The size of a struct is nothing for you to decide about what it "should" be. It is what it is, period.

    Struct and alignment and member padding is the compiler's job. You'll fare better not trying to second-guess it.

Reply
  • Normaly it should be 20

    Just to make this crystal clear: this statement expresses a fundamentally incorrect belief. The size of a struct is nothing for you to decide about what it "should" be. It is what it is, period.

    Struct and alignment and member padding is the compiler's job. You'll fare better not trying to second-guess it.

Children
  • It is true that the size of structures shouldn't be second-guessed. But it is very valuable to know why the compiler does what it does. With some knowledge, you can produce smaller structures.

    In embedded products, a better optimized size can be the difference between fitting all variables in the existing RAM or not. For PC-class processors, an optimal order of the individual fields can make the struct fit in one instead of two cache lines, or can make one extra struct fit in the same cache line. The speed difference can be very significant.

    But in the end, it's the sizeof operator that is king. Any code that assumes struct sizes instead of using the sizeof operator are highly nonportable.