Re: [問題] Variable decl followed by colon in struct
※ 引述《illjay0404 (尋找值得愛的人~*)》之銘言:
: 借標題詢問...
: 最近剛好也有碰到類似的問題 ,看完各位大大解釋後
: 又順便再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...
看你的描述,你的 bcb5 採用的方法應該是不硬接的方式!
#pragma pack(push,1)
struct SBitField {
unsigned char Seconds:5;
unsigned char Minutes:6;
unsigned char Hours :5;
};
#pragma pack(pop)
1. 一開始看到紅色 char 先 alloc 1Byte 出來,然後 Seconds 佔 5bits(剩3bits)
2. 接下來看到綠色 char 跟前面的型態一樣(同樣都是char)
剛剛剩餘空間還有 3bits 然後 Minutes 佔 6bits,空間不夠
所以另開空間 1Byte 出來(剩餘2bits)
3. 接下來看到黃色 char 跟前面的型態一樣(同樣都是char)
剛剛剩餘空間還有 2bits 然後 Hours 佔 5bits,空間不夠
所以另開空間 1Byte 出來(剩餘3bits)
所以 sizeof(SBitField) = 3
===================================
#pragma pack(push,1)
struct SBitField {
unsigned short Seconds:5;
unsigned short Minutes:6;
unsigned short Hours :5;
};
#pragma pack(pop)
1. 一開始看到紅色 short 先 alloc 2Bytes 出來,然後 Seconds 佔 5bits(剩11bits)
2. 接下來看到綠色 short 跟前面的型態一樣(同樣都是short)
剛剛剩餘空間還有 11bits 然後 Minutes 佔 6bits,所以不用另外開空間(剩5bits)
3. 接下來看到黃色 short 跟前面的型態一樣(同樣都是short)
剛剛剩餘空間還有 5bits 然後 Hours 佔 5bits,所以不用另外開空間(全部用完)
所以 sizeof(SBitField) = 2
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 36.225.171.190
推
12/27 08:42, , 1F
12/27 08:42, 1F
→
12/27 08:43, , 2F
12/27 08:43, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章