[英]Trying to reverse a string in place
I am trying to reverse a null terminated string in place in C++. 我试图在C ++中反转一个以null终止的字符串。 I have written the code below:
我写了下面的代码:
//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;
}
However, when I run this C++ program , I get aa write access violation inside the while loop at the statement : *str = *end ;
但是,当我运行此C ++程序时,我在while循环中的语句中遇到写访问冲突:
*str = *end ;
Even though this is fairly simple, I can't seem to figure out the exact reason I am getting this error. 即使这很简单,我似乎也无法弄清楚出现此错误的确切原因。
Could you please help me identify the error? 您能帮我找出错误吗?
char *str = "hello world";
is a pointer to a string literal, and can't be modified. 是指向字符串文字的指针,不能修改。 String literals reside in read-only memory and attempting to modify them results in undefined behavior .
字符串文字驻留在只读存储器中,尝试对其进行修改将导致未定义的行为 。 In your case, a crash.
就您而言,是当机。
Since this is clearly an assignment, I won't suggest using std::string
instead, since it's good to learn these things. 由于这显然是一项任务,因此我不建议改用
std::string
,因为学习这些东西很不错。 Use: 采用:
char str[] = "hello world";
and it should work. 它应该工作。 In this case,
str
would be an automatic-storage (stack) variable. 在这种情况下,
str
将是一个自动存储(堆栈)变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.