我的strcpy哪里错了?

predrag 2005-03-09 06:05:08
void mystrcpy (char* to, const char* from)
{
to = new char[mystrlen(from)+1];
for (; *from != 0; ++from, ++to)
{
*to = *from;
}
*to = 0;
}
运行时说一段内存不能读,正确的该怎么写?
...全文
182 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
pcboyxhy 2005-03-09
  • 打赏
  • 举报
回复
void mystrcpy (char* to, const char* from) //传的是 to的值,不是地址
{
to = new char[mystrlen(from)+1]; //改变不了调用函数的地方的 to的值
for (; *from != 0; ++from, ++to)
{
*to = *from;
}
*to = 0;
}


还是用传地址吧。


void foo(char *p)
{
p=new char;
}

char *s=new char;
foo(s); //执行后s的值没有改变
llf_hust 2005-03-09
  • 打赏
  • 举报
回复
#include<stdio.h>
#include<ctype.h>
#include<assert.h>
void mystrcpy (char* to, const char* from)
{
assert((to != NULL) && (from != NULL));
while( (*to++ = *from++) != '\0');
}

main()
{
char s[20];
char *p = "abcd";
clrscr();
mystrcpy(s,p);
puts(s);
getche();
}

我这个通过测试了
predrag 2005-03-09
  • 打赏
  • 举报
回复
还是不行啊,是不是我得main也错了:
int main()
{

const char* temp = "predrag";
char *target;

mystrcpy(target, temp);
cout << target << endl;
return 0;
}
avalonBBS 2005-03-09
  • 打赏
  • 举报
回复
const char * mystrcpy (char *to, const char *from)
{
char *temp=to;

for (; *from; ++from,++temp)
*temp = *from;

*temp = '\0';

return to;
}


int main()
{
char * a="abcdefg";
char *p = new char[ strlen(a)+1 ];
mystrcpy(p,a);
puts( p );

return 0;
}
llf_hust 2005-03-09
  • 打赏
  • 举报
回复
void mystrcpy (char* to, const char* from)
{
assert((to != NULL) && (from != NULL))
while( (*to++ = *from++) != '\0')
NULL;
}
wyystxl 2005-03-09
  • 打赏
  • 举报
回复
void mystrcpy (char* to, const char* from)
{
to = new char(strlen(from)+1);
while(!*from)
*to++ = *from++;
*to = '\0';
}

69,369

社区成员

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

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