The compiler is free to allocate as many bytes for a struct as it feels appropriate. If you use pragma pack then it should generate a size like you expect, but I'm not sure if that's guaranteed.
Basically, computers access memory more efficiently on addresses which are multiples of 4 or 16. Some types in fact *require* this alignment. Depending on compiler settings, therefore, the fields of the struct may not be exactly adjacent in memory; padding for alignment may be inserted by the compiler. Praga pack instructs the compiler specifically *not* to do this.
So that means these extra bytes depending on compiler and for safe handling of memory ?
I'm not quite sure what you're asking here. The choice of struct padding is dependent upon the compiler and the compile options and may change if you build in a different environment.
Te reason it does that is because most computers perform much better if your memory is WORD aligned. Usually a WORD is 4 bytes, so your compiler will expand and ever rearrange your struct to make that happen. You can stop the compiler from doing any rearranging by wrapping it in extern "C"{}, but even that will cause padding for alignment.
Te reason it does that is because most computers perform much better if your memory is WORD aligned. Usually a WORD is 4 bytes, so your compiler will expand and ever rearrange your struct to make that happen. You can stop the compiler from doing any rearranging by wrapping it in extern "C"{}, but even that will cause padding for alignment.
This claim sparked my curiosity, as I was taught that elements in structs can't be re-arranged, ever, in C or C++. So I investigated a bit. I found these two interesting answers:
Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1)
Originally Posted by C99 Section 6.7.2.1
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.
Long story short, it can't.
So yeah, that means the order of declaration can make a difference in the final struct size.
Unless you are on a very space-bound system though, I wouldn't worry too much about it, and declare elements in an order that makes sense to a human operator. And respect things like add new elements at the bottom, this makes it easier for change tacking.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Bookmarks