请高手解释一下

5ibiancheng 2003-11-09 11:07:59
为什么下面的代码strDest得不到正确的值
char* strSrc = "wang";
char *strDest=new char[10];

int i=0;

while ( (*strDest++ = *strSrc++) != '\0' );

在while 循环中打印*strSrc的值是正确的,但是打印*strDest则不正确
...全文
27 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
superholly 2003-11-09
  • 打赏
  • 举报
回复
#include<iostream>
using namespace std;
int main()
{
char* strSrc = "wang";
char *strDest=new char[10];
int i=0;

while ( (*strDest++ = *strSrc++) != '\0' )
{
cout<<*(strDest-1);
}
cout<<endl;
return 0;
}
strDest指针加了1,因此,printf---*strDest内容是不确定的

Wolf0403 2003-11-09
  • 打赏
  • 举报
回复
char* strSrc = "wang";
char *strDest=new char[10];
int i=0;
while (*strDest++ = *strSrc++)
i++;
strDest -= i;
printf("%s\n", strDest); 试试看。没调试,太晚了,开编译器怕吵
tuxw 2003-11-09
  • 打赏
  • 举报
回复
循环结束后 strDest 已经向后移了 strlen( strScr ) 个位置, 而不再指向你 new 出来的那块内存的开始了
zhusunme 2003-11-09
  • 打赏
  • 举报
回复
这样就可以了:
#include<stdio.h>
void main()
{
char* strSrc = "wang";
char *strDest=new char[10];

int i=0;

while ( (*strDest = *strSrc) != '\0' )
{
printf("%c",*strDest);
strDest++;
strSrc++;
}
}

69,378

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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