1
我想在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 != '\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循環中AA寫訪問衝突的聲明:*str = *end ;
即使這是相當簡單的,我似乎無法弄清楚我得到這個錯誤的確切原因。
你能幫我找出錯誤嗎?
非常感謝!來認識一件新事物! –