2012-09-07 61 views
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 ;

即使這是相當簡單的,我似乎無法弄清楚我得到這個錯誤的確切原因。

你能幫我找出錯誤嗎?

回答

5
char *str = "hello world"; 

是一個指向字符串文字的指針,無法修改。字符串文字駐留在只讀內存中,並嘗試修改它們導致未定義的行爲。在你的情況下,崩潰。

由於這顯然是一項任務,因此我不會建議使用std::string,因爲學習這些東西很好。使用:

char str[] = "hello world"; 

它應該工作。在這種情況下,str將是一個自動存儲(堆棧)變量。

+0

非常感謝!來認識一件新事物! –