我的字符串拷贝函数有什么问题

smilenot 2011-09-01 07:38:39

#include <assert.h>
#include <iostream>
using namespace std;
char* mystrcpy(char* dest,const char* source)
{
assert(dest!=NULL&&source!=NULL);
while(*dest++ = *source++);
return dest;
}
int main()
{
int a = 3;
char *dest;
dest = (char*)malloc(10);
cout << mystrcpy(dest,"hello") << endl;
return 0;
}


为什么mystrcpy函数执行完了以后dest内存里面仍然没有我的东西,我跟踪发现*dest = *source++ 这句话好像不能赋值,是怎么回事??
...全文
67 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
就想叫yoko 2011-09-02
  • 打赏
  • 举报
回复
pengzhixi 应该是手误了
yuqangy 2011-09-01
  • 打赏
  • 举报
回复
楼上正解
hongwenjun 2011-09-01
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 pengzhixi 的回复:]

C/C++ code
char* mystrcpy(char* dest,const char* source)
{
assert(dest!=NULL&&source!=NULL);
char *ptr=dest;
while(*dest++ = *source++);
return dest;
}
[/Quote]

return ptr; // 应该这样吧
pengzhixi 2011-09-01
  • 打赏
  • 举报
回复
char* mystrcpy(char* dest,const char* source)
{
assert(dest!=NULL&&source!=NULL);
char *ptr=dest;
while(*dest++ = *source++);
return dest;
}
zjxylc 2011-09-01
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 smilenot 的回复:]

引用 1 楼 zjxylc 的回复:
C/C++ code


#include <assert.h>
#include <iostream>
using namespace std;
void mystrcpy(char* dest,const char* source)
{
assert(dest!=NULL&amp;&amp;source!=NULL);
……
[/Quote]

我这运行正常的,你原来的返回的dest指针指向的是"hello" 中'/0'的地址,所以会以'/0'地址开始显示会出现乱码的。
TitanQuest 2011-09-01
  • 打赏
  • 举报
回复
return dest
草,
smilenot 2011-09-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 zjxylc 的回复:]
C/C++ code


#include <assert.h>
#include <iostream>
using namespace std;
void mystrcpy(char* dest,const char* source)
{
assert(dest!=NULL&&source!=NULL);
while(*dest++ = *sou……
[/Quote]

也是不行的
zjxylc 2011-09-01
  • 打赏
  • 举报
回复

#include <assert.h>
#include <iostream>
using namespace std;
void mystrcpy(char* dest,const char* source)
{
assert(dest!=NULL&&source!=NULL);
while(*dest++ = *source++);
}
int main()
{
int a = 3;
char *dest;
dest = (char*)malloc(10);
mystrcpy(dest,"hello");
cout << dest << endl;
return 0;
}


这样就行了

64,642

社区成员

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

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