看板 C_and_CPP 關於我們 聯絡資訊
借標題詢問... 最近剛好也有碰到類似的問題 ,看完各位大大解釋後 又順便再google一下 ,發現衍伸性的問題 我使用平台是bcb5 #pragma pack(push,1) struct SBitField { unsigned char Seconds:5; unsigned char Minutes:6; unsigned char Hours :5; }; #pragma pack(pop) sizeof(SBitField) 結果是 3 又再google後發現... C99 6.7.2.1 Structure and union specifier: An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. 然後自己又試了一下.... #pragma pack(push,1) struct SBitField { unsigned short Seconds:5; unsigned short Minutes:6; unsigned short Hours :5; }; #pragma pack(pop) sizeof(SBitField) 結果結果就變成2了 我想問的是~這感覺是不是像alignment ? 當編譯器配置時發現Char Minutes 類別空間不夠擺入 char Seconds 所以再配置另一個Char類別空間 ,擺放給char Seconds 然後char Hours也是 ,所以sizeof後是3 ? short是直接大類別空間擺放bit-field所以是2 ? 請各問大大解除小弟疑疑惑 Orz... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.124.107.139 ※ 編輯: illjay0404 來自: 59.124.107.139 (12/26 10:58)
LPH66:你引的標準那段話就是在說碰到剩下的不夠時要另開還是硬接 12/26 12:19
LPH66:是 implementation-defined 隨實作決定的 12/26 12:19
LPH66:那你的編譯器就只是選擇另開這個選項而已 12/26 12:20
illjay0404:了解!!所以空間的分配是由編譯器決定! 12/27 08:50