C++ 访问冲突写入位置处未处理的异常

C++ 访问冲突写入位置处未处理的异常,c++,exception,C++,Exception,我试图写一个简单的反向字符串程序,并得到上述错误。我无法理解我做错了什么 void reverse(char *str) { char *end, *begin; end = str; begin = str; while (*end != '\0') { end++; } end--; char temp; while (begin < end) { temp = *begin; *begin++ = *end; //This is the lin

我试图写一个简单的反向字符串程序,并得到上述错误。我无法理解我做错了什么

void reverse(char *str) {
char *end, *begin;
end = str;
begin = str;

while (*end != '\0') {
    end++;
}

    end--;

char temp;

while (begin < end) {
    temp = *begin;
    *begin++ = *end; //This is the line producing the error
    *end-- = temp;
}
}

void main() {
char *str = "welcome";
reverse(str);
}
void反向(char*str){
字符*结束,*开始;
end=str;
begin=str;
而(*end!='\0'){
end++;
}
结束--;
焦炭温度;
while(开始<结束){
温度=*开始;
*begin++=*end;//这是产生错误的行
*结束--=温度;
}
}
void main(){
char*str=“欢迎”;
反向(str);
}

我需要你的帮助。谢谢。

您正在尝试修改字符串文字,这是未定义的行为。如果要修改,这将是在
main
中声明
str
的有效方法:

char str[] = "welcome";
另外,您正在将
end
赋值给
str
的开头,然后执行以下操作:

end--;
它在为字符串分配的内存之前递减指针,这是未定义的行为。我猜你是想这么做的:

end = str+ (strlen(str)-1);

对不起,我忘了复制一些代码,我将立即(在结束之前)更新它。您的解决方案有帮助。我必须以这种方式初始化字符串,程序运行正常。非常感谢。