C語言中結構體與字元陣列之間的相互轉換
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma pack(push) //儲存對齊狀態
#pragma pack(1)
typedef struct strcChange
{
unsigned char A;
unsigned int B;
}STRU_CHANGE;
#pragma pack(pop)
如果在未加位元組對齊的情況下,那麼A變數的後面需要自動填充三個位元組,那麼直接將結構體取地址後複製到另一個數組中,實際上所需佔用的記憶體大小是8個byte。
typedef struct strcChange2
{
unsigned char A;
unsigned char B;
unsigned char C;
}STRU_CHANGE2;
int main()
{
STRU_CHANGE strChangeData1;
STRU_CHANGE strChangeData2;
STRU_CHANGE * pstrChangeData1;
unsigned char * pucData;
char C[10];
strChangeData1.A = 0x01;
strChangeData1.B = 0x05040302;
strChangeData2.A = 0x11;
strChangeData2.B = 0x55443322;
pucData = (unsigned char *)(&strChangeData2);
printf("pucData[0] = 0x%x\n", pucData[0]);
printf("pucData[1] = 0x%x\n", pucData[1]);
printf("pucData[2] = 0x%x\n", pucData[2]);
printf("pucData[3] = 0x%x\n", pucData[3]);
printf("pucData[4] = 0x%x\n", pucData[4]);
memcpy(C, &strChangeData1, sizeof(strChangeData1));
pstrChangeData1 = (STRU_CHANGE *)((char*)C);
printf("STRU_CHANGE.A = 0x%x\n", pstrChangeData1->A);
printf("STRU_CHANGE.B = 0x%08x\n", pstrChangeData1->B);
system("PAUSE");
return 0;
}