关于ntohl,htonl,为什么输出是0啊

chenyi3315 2008-09-11 11:36:06
int main(int argc,char *argv[])
{
char *pMsg = new char[4];
int nTmpLen = htonl(93);
strncpy(pMsg,(char *)&nTmpLen,4);
int nLen;
strncpy((char*)&nLen,pMsg,4);
nLen = ntohl(nLen);
cout<<nLen<<endl;
delete pMsg;
pMsg = NULL;
return 0;
}

在linux上。。。
...全文
242 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenyi3315 2008-09-11
  • 打赏
  • 举报
回复
多谢,多谢!
xkyx_cn 2008-09-11
  • 打赏
  • 举报
回复
strncpy遇到'\0'要终止拷贝的
xkyx_cn 2008-09-11
  • 打赏
  • 举报
回复
使用memcpy:

int main(int argc,char *argv[])
{
char *pMsg = new char[4];
int nTmpLen = htonl(93);
memcpy(pMsg,(char *)&nTmpLen,4);
int nLen;
memcpy((char*)&nLen,pMsg,4);
nLen = ntohl(nLen);
cout<<nLen<<endl;
delete pMsg;
pMsg = NULL;
return 0;
}
Jeffrey84 2008-09-11
  • 打赏
  • 举报
回复
nTmpLen 0x5d000000 int
低位是0,(char *)&nTmpLen 等于指向的第一个char就是\0,所以是0长度字符串
Jeffrey84 2008-09-11
  • 打赏
  • 举报
回复
[Quote=引用楼主 chenyi3315 的帖子:]
C/C++ codeint main(int argc,char *argv[])
{
char *pMsg = new char[4];
int nTmpLen = htonl(93);
strncpy(pMsg,(char *)&nTmpLen,4);
int nLen;
strncpy((char*)&nLen,pMsg,4);
nLen = ntohl(nLen);
cout<<nLen<<endl;
delete pMsg;
pMsg = NULL;
return 0;
}


在linux上。。。
[/Quote]
pMsg仍然是长度为0的字符串

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧