C ++:交换指向变量

时间:2012-12-08 05:39:58

标签: c++ pointers swap

  

可能重复:
  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的指向值,但似乎有些东西被搞砸了。在此先感谢您的帮助!

3 个答案:

答案 0 :(得分:7)

代码看起来很好。最可能的问题是允许编译器假定字符串文字未被修改,因此它可以将它们放在只读内存中。尝试

char s[] = "Hello";

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

答案 1 :(得分:1)

@j_random_hacker的另一种解决方案:

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

... rest of your program ...

delete[] buffer;

这为C风格的字符串正确分配内存,然后可以通过任何函数进行修改。当然,您需要添加<string.h>标头才能访问strcpystrlen

答案 2 :(得分:0)

缺少strlen()的头文件。

其次,它会抛出一个警告 - 从字符串常量到char *的过时转换,@ j_random_hacker的解决方案似乎解决了这个问题。

相关问题