问题
Possible Duplicate: Why isn't sizeof for a struct equal to the sum of sizeof of each member?
In the following code, the value of structSize
is different depending on whether it's executed on an Arduino vs my PC (Ubuntu 11.04 x64).
struct testStruct{
uint8_t val1;
uint16_t val2;
};
...
uint_8_t structSize = sizeof(testStruct);
On my PC, the value of structSize
is 4, and on my Arduino the value of structSize
is 3 (as expected).
Where is this 4th byte coming from?
回答1:
Actually, I would have expected the size to be 4, because uint16_t
is usually aligned to 16 bits.
The extra byte is padding inserted between the members to keep the alignment of uint16_t
.
This is compiler dependent though. Arduino might be more selfish with memory and probably doesn't care that much about alignment. (possible explanation)
回答2:
It's because of differing ABIs between the two CPU types you're targetting. It seems like that on Arduino (ARM v7?) differs from x86_64.
On x86 at least, uint16_t
(short) is generally aligned to a two-byte boundary. In order to achieve that, a byte of padding is inserted after val1
. I expect the same is true on x86_64.
There's lots of information about this in the Wikipedia article on x86 structure padding.
You may be able to achieve what you want using the #pragma pack
directive … but here be dragons, don't tell anyone I suggested it :)
回答3:
If you are designing a database engine to run on a mobile processor then carry on, but for most anything else you are writing, your time will be better spent on building functionality using type systems that are easy to understand and relatively standard across architectures.
来源:https://stackoverflow.com/questions/11346350/sizeof-difference-between-c-on-pc-and-arduino