64,642
社区成员
发帖
与我相关
我的任务
分享
typedef struct _MsgHead
{
int MsgLen;
int MsgType;
SOCKET sock;
} tMsgHead, *ptMsgHead;
const int Len_tMsgHead = sizeof(tMsgHead);
typedef struct _Msg
{
tMsgHead head;
void *buf;
}tMsg, *ptMsg;
#define TEST_MSG_TYPE 1000
typedef struct _TestMsg
{
int count;
DWORD dw;
char msg[32];
} tTestMsg, *ptTestMsg;
//...
int main()
{
tMsg *pMsg = (tMsg *)malloc(Len_tMsgHead + sizeof(tTestMsg));
pMsg->head.sock = 0;
pMsg->head.MsgType = TEST_MSG_TYPE;
pMsg->head.MsgLen = sizeof(tTestMsg);
tTestMsg t0;
t0.count = 0; t0.dw = 1; strcpy(t0.msg, "test only");
// 下面3条赋值语句,都是取pMsg->buf的地址,你认为哪个正确?为什么?
void *p1 = &pMsg->buf; // (1)
void *p2 = pMsg + Len_tMsgHead; // (2)
void *p3 = (char *)pMsg + Len_tMsgHead; // (3)
// 下面2条拷贝内存到pMsg->buf,哪一个正确?为什么?
memcpy(&pMsg->buf, &t0, sizeof(tTestMsg)); // (4)
memcpy(pMsg + Len_tMsgHead, &t0, sizeof(tTestMsg)); // (5)
}