"); //-->
#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; }总结
服务端使用了 #pragma pack(n) , 客户端接收也必须同时对变量结构体进行 #pragma pack(n) 处理, 不然对齐方式不同,直接赋值会错乱。
*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。