本文介绍了我的strcpy有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让 strcpy
自己。它应该工作,我甚至复制和粘贴(几乎完全代码)从某人在这里关于 strcpy
。两者都给我一个分段错误。
char * strcpy(char * destination,const char * source)
{
while((* destination ++ = * source ++)!='\0')
;
return destination;
}
此代码有什么问题?
char * a =hello
cout< strcpy(a,Haha)<< endl;
解决方案
因此,当你调用 strcpy $ c $
char a [] =hello;
cout< strcpy(a,Haha)<< endl;
strcpy
函数,复制后,目标
将指向字符串的结尾,需要返回字符串的开头
I tried to make strcpy
myself. It should work, I even copied and pasted the (almost exact code) from someones post here about strcpy
. Both give me a "Segmentation Fault".
char* strcpy(char * destination, const char * source)
{
while( (*destination++ = *source++) != '\0' )
;
return destination;
}
What's wrong with this code?
char* a = "hello";
cout << strcpy(a, "Haha") << endl;
解决方案 You are trying to write to data segment since "hello"
is stored there.
Therefore, when you call strcpy
you get segmentation fault.
Try:
char a[] = "hello";
cout << strcpy(a, "Haha") << endl;
instead.
EDIT: Inside your strcpy
function, after the copy, destination
will point to end of the string, you need to return beginning of the string instead.
这篇关于我的strcpy有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!