Roh*_*wal 1 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;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行这个C++程序时,我在语句的while循环中得到了一个写访问冲突: *str = *end ;
虽然这很简单,但我似乎无法弄清楚我收到此错误的确切原因.
你能帮我辨认一下这个错误吗?
char *str = "hello world";
Run Code Online (Sandbox Code Playgroud)
是指向字符串文字的指针,不能修改.字符串文字驻留在只读内存中,尝试修改它们会导致未定义的行为.在你的情况下,崩溃.
由于这显然是一项任务,我不会建议使用std::string,因为学习这些东西是好的.使用:
char str[] = "hello world";
Run Code Online (Sandbox Code Playgroud)
它应该工作.在这种情况下,str将是一个自动存储(堆栈)变量.