试图将字符串反转到位

时间:2012-09-07 09:12:53

标签: c++ string reverse

我试图在C ++中反转一个空终止的字符串。我写了下面的代码:

//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 != '\0')
    {
        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 ;

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

你能帮我辨认一下这个错误吗?

1 个答案:

答案 0 :(得分:5)

char *str = "hello world";

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

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

char str[] = "hello world";

它应该有效。在这种情况下,str将是自动存储(堆栈)变量。

相关问题