PC 和 Arduino 上的 C++ 之间的 Sizeof() 差异 [英] Sizeof() difference between C++ on PC and Arduino

查看:31
本文介绍了PC 和 Arduino 上的 C++ 之间的 Sizeof() 差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:为什么结构体的 sizeof 不等于每个成员的 sizeof 之和吗?

在下面的代码中,structSize 的值取决于它是在 Arduino 还是我的 PC (Ubuntu 11.04 x64) 上执行.

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);

在我的 PC 上,structSize 的值为 4,而在我的 Arduino 上,structSize 的值为 3(如预期).

On my PC, the value of structSize is 4, and on my Arduino the value of structSize is 3 (as expected).

这第 4 个字节从何而来?

Where is this 4th byte coming from?

推荐答案

实际上,我希望大小为 4,因为 uint16_t 通常对齐为 16 位.

Actually, I would have expected the size to be 4, because uint16_t is usually aligned to 16 bits.

额外的字节是在成员之间插入填充以保持uint16_t的对齐.

The extra byte is padding inserted between the members to keep the alignment of uint16_t.

虽然这取决于编译器.Arduino 可能对内存更自私,并且可能不太关心对齐.(可能的解释)

This is compiler dependent though. Arduino might be more selfish with memory and probably doesn't care that much about alignment. (possible explanation)

这篇关于PC 和 Arduino 上的 C++ 之间的 Sizeof() 差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆