代码之家  ›  专栏  ›  技术社区  ›  x.509

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

  •  2
  • x.509  · 技术社区  · 16 年前
    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;
        }
    }
    

    3 回复  |  直到 16 年前
        1
  •  11
  •   Konrad Rudolph    16 年前

    问题是它使用C风格字符串而不是C++风格字符串。特别是,你显然是在试图写一个常量 :

    char const* str = "I cannot be written to";
    

    const 这里是为了向后兼容,但是 文字仍然是常量 .

    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;
    }
    
        2
  •  1
  •   Jerry Coffin    16 年前

    我猜问题在于你怎么称呼它,可能是用一个字符串,比如:

    reverse("This is a string");
    

    或: char*string=“这是一个字符串”;

    或者其他一些小的变化。在任何情况下,您都试图写入一个字符串文本,这会产生未定义的行为。

    既然你明显使用C++,我会考虑使用 std::string 取而代之的是:

    void reverse(std::string &s) { 
        int j=s.length()-1;
        for (int i=0; i<j; i++, j--) {
            // ..
        }
    }
    
        3
  •  0
  •   Stephen    16 年前

    const char* 还是字符串文字?

    你想倒车吗

    reverse("foo");
    

    或

    char *s = "foo";
    reverse(s);
    

    那个 strdup .

    char *s = strdup("foo");
    reverse(s);
    free(s, strlen(s));
    

    另外请注意,您的问题被标记为c++,因此您可能应该使用 std::string .