我试着strcpy自己做.它应该工作,我甚至复制和粘贴(几乎确切的代码)来自这里的某些人 strcpy.两者都给我一个"分段错误".
char* strcpy(char * destination, const char * source)
{
while( (*destination++ = *source++) != '\0' )
;
return destination;
}
Run Code Online (Sandbox Code Playgroud)
这段代码出了什么问题?
char* a = "hello";
cout << strcpy(a, "Haha") << endl;
Run Code Online (Sandbox Code Playgroud)
您正在尝试覆盖字符串文字.这会导致未定义的行为.a改为声明为数组:
char a[] = "hello";
Run Code Online (Sandbox Code Playgroud)
您的strcpy实现也有一个错误(假设正常的语义).它应该返回一个指向目标缓冲区开头的指针,而不是结尾.