访问冲突写入位置出现未处理的异常

Unhandled exception at Access violation writing location

本文关键字:未处理 异常 位置 访问冲突      更新时间:2023-10-16

我正在尝试编写一个简单的反向字符串程序,但却出现了上述错误。我无法理解我做错了什么。

void reverse(char *str) {
char *end, *begin;
end = str;
begin = str;
while (*end != '') {
    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);
}

需要你的帮助。谢谢

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

char str[] = "welcome";

此外,您将end分配给str的开头,然后执行以下操作:

end--;

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

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