C语言&嵌入式踩坑
1-结构体字节对齐
假设有这样一个结构体
typedef struct
{
u16 emission;
u16 cylinder_num;
}motor engine;
此结构体在内存中的存储方式为
Byte 0 1
# # (u16 emission)
# # (u16 cylinder_num)
这是 2 Byte 对齐的
若在内存中要求为 4 Byte 对齐的情况下,可能会导致内存踩踏
可将其修改为
typedef struct
{
u16 emission;
u32 cylinder_num;
}motor engine;
此时在内存中的存储方式为
Byte 0 1
# # (u16 emission)
# # # # (u32 cylinder_num)
这是 4 Byte 对齐的,可避免内存踩踏
相关知识关键词:结构体字节对齐
2-不同长度变量强转
Byte 3 2 1 0
# # # # (u16)
# # (u8)
u16 强制转换为 u8 的过程,是直接取 Byte 3 2 的数据,即将u16右移8位得到 u8,同理 u32 转 u16 、u64 转 u32 也是同理

浙公网安备 33010602011771号