Re: [問題] struct大小
alignment 的問題
為了效率,compiler 有時候會把資料成員排在某些倍數(例如4)的位置
typedef struct _bmp_file_header
{
unsigned short bfType; 2
unsigned long bfSize; 4
unsigned short bfReserved1; 2
unsigned short bfReserved2; 2
unsigned long bfOffBits; 4
}BMPFILEHEADER;
應該是要配14個
但是如果這樣配
typedef struct _bmp_file_header
{
unsigned short bfType; 4 本來是 2
unsigned long bfSize; 4
unsigned short bfReserved1; 2
unsigned short bfReserved2; 2
unsigned long bfOffBits; 4
}BMPFILEHEADER;
總共配16個
效能會更好
結果就變成第二個欄位以後的位置全部跑掉
如果你是從檔案讀進來的話
第二個欄位以後的資料就全錯 XD
解決方法......
typedef struct _bmp_file_header
{
unsigned char foo[14] ;
}BMPFILEHEADER;
這樣就 14 byte
想要存取資料的時候用很醜的轉型
像是 offset = *((unsigned long *)(foo+10)) ;
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.129.180
推
04/23 03:08, , 1F
04/23 03:08, 1F
推
04/23 03:10, , 2F
04/23 03:10, 2F
推
04/23 03:10, , 3F
04/23 03:10, 3F
→
04/23 03:11, , 4F
04/23 03:11, 4F
推
04/23 03:11, , 5F
04/23 03:11, 5F
→
04/23 03:16, , 6F
04/23 03:16, 6F
推
04/23 03:23, , 7F
04/23 03:23, 7F
→
04/23 03:24, , 8F
04/23 03:24, 8F
推
04/23 03:25, , 9F
04/23 03:25, 9F
→
04/23 03:23, , 10F
04/23 03:23, 10F
→
04/23 03:26, , 11F
04/23 03:26, 11F
→
04/23 03:27, , 12F
04/23 03:27, 12F
推
04/23 03:28, , 13F
04/23 03:28, 13F
→
04/23 03:29, , 14F
04/23 03:29, 14F
推
04/23 03:30, , 15F
04/23 03:30, 15F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章