我在VC6和DEVC++中运行都不行,错误出现在for(;*from!=\0;from++,to++)
void copy_string(char *from, char *to)
{
for(;*from!=\0;from++,to++)
*to = *from;
*to=\0;
printf("to=%s\n",to);
}
int main(int argc, char* argv[])
{
char *a ="I am a teacher.";
char *b ="you are a student.";
printf("before copy:\n");
printf("a=%s\nb=%s\n\n",a,b);
copy_string(a,b);
return 0;
}
为什么阿
你该成++from 和++to 看看
我在网把,没编译器,我不知道
是书上源码吗?如果是的话,也太不负责任了,char *a,char *b指向了静态存储区的代码,是不可以改变的!代码是错的!
int main(int argc, char* argv[])
{
char *a ="I am a teacher.";
char b[1024] = {0};
printf("a=%s\nb=%s\n\n",a,b);
copy_string(a,b);
return 0;
}
而且你的copy函数也写错了 最后输出的指针to的位置也没对嘛
#include <iostream.h>
#include <string.h>
void copy_string(char *from, char *to)
{
char *before=to;
for(;*from!=\0;from++,to++)
*to = *from;
*to=\0;
cout<<"to="<<before<<endl;
}
int main()
{
char *a ="I am a teacher.";
char *b =new char [strlen("you are a student.")];
strcpy(b,"you are a student.");
cout<<"before copy:\n";
cout<<"a="<<a<<"b="<<b<<endl;
copy_string(a,b);
return 0;
}
char *a ="I am a teacher.";
char *b ="you are a student.";
垃圾,这里指的是常量区域,不可改变的,但Linux下是可以改变的
在C++中char *a ="I am a teacher.";
与const char *a="I am a teacher.";
是等价的,不能改变你把char *b ="you are a student.";改成char *b =NULL;
b=malloc(strlen(a));就可以了
strlen(a)<strlen(b)
应该给a重新分配足够大小的内存