我正在嘗試組合和統一來自 int 和 short 的位元組序列
在除錯和讀取記憶體時,它是這樣對齊的 [FF FF FF FF 00 00 00 00]
[FF FF FF FF FF FF 00 00] 既然我正在使用聯合,它不應該看起來像這樣嗎?
union uniteByte{
unsigned int blockOne;
unsigned short blockTwo;
};
union uniteByte testing;
testing.blockOne =0xffffffff; //4294967295
testing.blockTwo = 0xffff; //65535
printf("%zu\n",sizeof(testing)); // size is 4 why? shouldn't it be 6?
printf("%u\n",testing.blockOne); // 4294967295
printf("%u\n",testing.blockTwo); // 65535
printf("%p",&testing); //0x7ffeefbff4e0 [FF FF FF FF 00 00 00 00]
printf("%p",&testing.blockOne); //0x7ffeefbff4e0 <-- the address is the same as in blockTwo
printf("%p",&testing.blockTwo); //0x7ffeefbff4e0 <-- the address is the same as in blockOne
uj5u.com熱心網友回復:
a 的目的union是為每個成員使用重疊記憶體,因此大小是最大成員的大小,必要時加上填充。
如果您希望成員獨立,則必須使用struct. 要擺脫成員之間的填充,最后使用__attribute__((packed)).
請注意,這通常會對性能產生影響。在記憶體和暫存器之間移動數字的 CPU 操作通常具有對齊要求,這就是結構通常具有填充的原因。打包結構時,必須逐位元組移動資料,而不是使用單個指令來獲取數字的完整大小。因此,只有在記憶體效率非常高且您需要這種時空權衡時才應該這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419664.html
標籤:
