I am trying to reverse a null terminated string in place in C++. 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 a a write access violation inside the while loop at the statement : *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?