c++中的这个反向数组代码有什么问题?

What is the issue with this reverse array code in c++?

程序编译正常,但在 运行 时崩溃并显示: 进程终止,状态为 -1073741819

void reverse(char *str){

    char * end1 = str;
    char tmp = 'c';
    if(str){
        while(*end1){
            ++end1;
        }
        --end1;

        while(str<end1){
            tmp=*str;
            *str=*end1;
            *end1=tmp;
            str++;
            end1--;
        }
    }
}

有什么想法吗?

您的 reverse 实现绝对没有问题:只要您传递的字符串以 null 结尾且可写,您的代码就可以正常工作。

那一定是你调用的方式有问题。最常见的可能性是传递一个字符串文字,写入它是可能导致崩溃的未定义行为:

char *s = "quick brown fox";
reverse(s); // <<== This would be undefined behavior

Demo of your working code.