正在尝试将字符串反转到位

Trying to reverse a string in place

本文关键字:字符串      更新时间:2023-10-16

我正试图在C++中反向一个以null结尾的字符串。我已经写了下面的代码:

//Implement a function to reverse a null terminated string
#include<iostream>
#include<cstdlib>
using namespace std;
void reverseString(char *str)
{
    int length=0;
    char *end = str;
    while(*end != '')
    {
        length++;
        end++;
    }
    cout<<"length : "<<length<<endl;
    end--;
    while(str < end)
    {
        char temp = *str;
        *str++ = *end;
        *end-- = temp; 

    }
}
int main(void)
{
    char *str = "hello world";
    reverseString(str);
    cout<<"Reversed string : "<<str<<endl;
}

然而,当我运行这个C++程序时,我在while循环中的语句*str = *end ; 中遇到了写访问冲突

尽管这很简单,但我似乎无法弄清楚我出现这个错误的确切原因。

你能帮我找出错误吗?

char *str = "hello world";

是指向字符串文字的指针,无法修改。字符串文字存在于只读内存中,试图修改它们会导致未定义的行为。在你的情况下,一个崩溃。

由于这显然是一项任务,我不建议使用std::string,因为学习这些东西很好。用途:

char str[] = "hello world";

它应该起作用。在这种情况下,str将是一个自动存储(堆栈)变量。