以下結構體爲例說明:
typedef struct sys_data0
{
unsigned char databag_type;//1
int EPC[4]; //16
unsigned char segment_num;//1
unsigned char last_segment;//1
short data_length;//2
unsigned char user_data[netDATASIZE];//26
}net_data;
union xx
{
unsigned char buff[52];
net_data net_opma;
}tt;
在沒有進行#pragma pack(1)宏定義時,當給tt.net_opma中各個成員賦值時,
tt.net_opma.databag_type=0x10;//84
tt.net_opma.EPC[1]=0x98765432;
tt.net_opma.EPC[2]=0x11223344;
tt.net_opma.EPC[3]=0x55667788;
tt.buff[0]=0x10;
tt.buff[1]=0;
tt.buff[2]=0;
tt.buff[3]=0;
tt.buff[4]=0x32;
tt.buff[5]=0x54;
tt.buff[6]=0x76;
tt.buff[6]=0x98;
```````````````
可以看到第一個字節後面多出了3個字節,這是由於arm上默認的是4字節對齊的,第一個是char型,佔用一個字節,第二個是int型佔4個字節,內存中擺放如下:
00 00 00 0x10
0x98 0x76 0x54 0x32
··········
若採用了#pragma pack(1)後在內存中擺放如下,這樣就不會多出空着的3個字節了:
0x76 0x54 0x32 0x10
······· 0x98
#pragma pack()這個宏定義函數在結構體和聯合體中的用處還是蠻大的,嘿嘿。。