先直接上我原来的代码
#include <iostream>
#include <assert.h>
char * strcpy(char* s1,const char *s2){
assert(s1);
assert(s2);
char * temp=s1;
while((*s1++=*s2++)!='\0');
return temp;
}
int main(){
char *s3="abcde";
char *s4="bef";
std::cout<<strcpy(s3,s4)<<std::endl;
system("pause");
return 0;
}
这段代码在执行过程中会不断报以下错误:
这种情况实在让我很郁闷,我这种写法很标准啊,也没越界,怎么会报错呢。后来查了资料才想起来
,错的不是函数本身,而是main里传的参数就错了。
char *=某字符串,这种写法定义的是一个指针指向字符串常量,而字符串常量存储在C++的常量区,因此是不能修改的,我传参下去之后给s1赋值就会报错。这就有点像传参里的const char *s2了
应该改成数组的形式,char[]数组由系统自己分配空间,因此存储在栈区,就可以修改了。
修改后如下
#include <iostream>
#include <assert.h>
char * strcpy(char* s1,const char *s2){
assert(s1);
assert(s2);
char * temp=s1;
while((*s1++=*s2++)!='\0');
return temp;
}
int main(){
char s1[]="abcde"; //这里修改
char s2[]="bef"; //这里修改
std::cout<<strcpy(s1,s2)<<std::endl;
system("pause");
return 0;
}