这个c ++反向字符串函数有什么问题

x.5*_*509 2 c++ string

void reverse (char s[]){
int len = strlen(s);
int j = len - 1;
for (int i = 0; i < j; i++,j--){
    cout << s[i];
    char ch = s[i];
    s[i] = s[j]; //error line - giving exception, cannot write to the memory
    s[j] = ch;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Visual Studion 2008,我无法理解这里的问题是什么..:s ..我没有C++实践:$.

Kon*_*lph 11

问题是它使用C风格的字符串而不是C++风格的字符串.特别是,您显然正在尝试写入常量字符串文字:

char const* str = "I cannot be written to";
Run Code Online (Sandbox Code Playgroud)

C++允许省略const这里的向后兼容性,但文字仍然是常量.

最后,C++已经有了一个reverse功能:

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello world";
    std::reverse(str.begin(), str.end());
    std::cout << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 这个.std :: string和std :: reverse是要走的路. (2认同)