【问题标题】:C++: Swapping pointed-to variables [duplicate]C ++:交换指向变量[重复]
【发布时间】:2012-12-08 05:39:58
【问题描述】:

可能重复:
Why do I get a segmentation fault when writing to a string?

我有以下程序:

#include <iostream>
using namespace std;

void reverseString(char* first, char* last)
{
    while(first < last)
    {
        cout << *first << " " << *last << endl; //for debugging; prints 'H' and 'o' then crashes
        char temp = *last;
        *last = *first; //this line crashes the program
        *first = temp;
        first++;
        last--;
    }
}

int main()
{
    char* s = "Hello";
    reverseString(s, s + strlen(s) - 1);
    cout << s << endl;
}

但是,我在交换指针指向的值时遇到了麻烦。我认为 *p = *p1 应该只是将 p 的指向值设置为 p1 的指向值,但似乎有些问题。提前感谢您的帮助!

【问题讨论】:

  • 如果你不需要自己实现这个,首选std::reverse
  • 我知道,但我真的很想知道为什么它不像我设置的那样工作。顺便说一句,谢谢你的提示。
  • 您正在修改字符串文字。

标签: c++ pointers swap


【解决方案1】:

代码对我来说看起来不错。最可能的问题是允许编译器假设字符串文字没有被修改,因此它可以将它们放在只读内存中。试试

char s[] = "Hello";

main() 中,它会创建字符串文字的可写副本

【讨论】:

  • 成功了,谢谢!我从来不知道只读存储器。
【解决方案2】:

@j_random_hacker 的替代解决方案:

char* buffer = new char[32];
strcpy(buffer, "Hello");
reverseString(buffer, buffer + strlen(buffer) - 1);

... rest of your program ...

delete[] buffer;

这会为 C 风格的字符串正确分配内存,然后可以由任何函数修改。当然,您需要包含&lt;string.h&gt; 标头才能访问strcpystrlen

【讨论】:

  • 我会 +1,但你说“正确分配”的事实表明,在堆栈上使用本地数组(正如我建议的那样)在某种程度上是“不正确的”:-P
  • 不是。知道我决定何时释放我的数组时,我只是感到温暖和模糊! :)
【解决方案3】:

strlen() 的头文件丢失。

其次,它会引发警告 - 已弃用从字符串常量到 char* 的转换,@j_random_hacker 的解决方案似乎解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 2016-06-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2013-03-07
    相关资源
    最近更新 更多