我有这个结构:
typedef struct pkt {
unsigned int pktid;
unsigned int pkt_leng;
unsigned int strleng;
char* str;
};
在我的代码中,我正在这样做:
mystring = someFunctionWhoReturnString();
pkt* mypkt = (pkt*) malloc(sizeof(pkt));
mypkt -> pkt = htonl(C_MYPKT);
mypkt -> pkt_leng = htonl(sizeof(pkt));
mpykt -> strleng = htonl(mystring.lengh());
mypkt -> str = (char*)malloc(mystring.length());
strcpy(mypkt -> str, mystring.c_str(), mystring.length());
在此之后,如果我检查存储在 mypkt->str 上的内容,则该字符串就在那里。
但是当我收到 pkt 时,我只得到了一些垃圾(大小很好),假设得到了 char*(数据包中的其余数据可以到达)。
有一些聪明的方法可以在不使用具有静态大小的 char[] 的情况下完成这项任务吗?
我在 VC++ 2010 上工作。