问题描述
我想写一个函数来反转一个字符串,但我有这样的异常,当我做:* str ++ = * end;谁知道什么是什么原因?提前致谢。
void reverse(char * str)
{
char * end = str;
char temp;
if(str)
{
while(* end)
{
end ++;
}
end--;
while(str {
temp = * str;
* str ++ = * end;
* end - = temp;
}
}
}
机会是,你使用字符串文字调用函数:
reverse(ablewasiereisawelba);
您不能修改字符串文字而不调用未定义的行为,崩溃是对尝试的有效响应修改字符串文字。请确保您传递非常量数组:
char palindrome [] =ablewasiereisawelba
reverse(palindrome);
C ++ 2011标准ISO / IEC 14882:2011说:
通常,字符串文字放置在只读内存中,尝试修改一个字符串会导致崩溃。这当然是对调用未定义行为的完全合理的响应。
I am trying to write a function to reverse a string, but I got such exception when I am doing: *str++ = *end; anyone who knows what's the reason? Thanks in advance.
void reverse(char* str)
{
char *end = str;
char temp;
if(str)
{
while(*end)
{
end++;
}
end--;
while(str<end)
{
temp = *str;
*str++ = *end;
*end--=temp;
}
}
}
Chances are, you called the function with a string literal:
reverse("ablewasiereisawelba");
You can't modify string literals without invoking undefined behaviour, and crash is a valid response to an attempt to modify a string literal. Make sure you pass a non-constant array instead:
char palindrome[] = "ablewasiereisawelba";
reverse(palindrome);
The C++ 2011 standard, ISO/IEC 14882:2011 says:
Commonly, string literals are placed in readonly memory, and an attempt to modify one leads to a 'crash'. That is certainly a perfectly legitimate response to invoking undefined behaviour.
这篇关于访问冲突写入位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!