使用指针C++进行字符串反转

DrT*_*ran 6 c++ string reverse pointers char

可能重复:
为什么在写入字符串时会出现分段错误?

我想编写一个简单的C++函数是一个反转 string/ char[]只指针运算.我理解这个概念并且已经输入了代码.

我有以下.cpp文件:

#include <iostream>
using std::cout;
using std::endl;

void reverse(char* target) //Requirements specify to have this argument
{
    cout << "Before :" << target << endl; // Print out the word to be reversed
    if(strlen(target) > 1) // Check incase no word or 1 letter word is placed
    {
        char* firstChar = &target[0]; // First Char of char array
        char* lastChar = &target[strlen(target) - 1]; //Last Char of char array
        char temp; // Temp char to swap
        while(firstChar < lastChar) // File the first char position is below the last char position
        {
            temp = *firstChar; // Temp gets the firstChar
            *firstChar = *lastChar; // firstChar now gets lastChar
            *lastChar = temp; // lastChar now gets temp (firstChar)
            firstChar++; // Move position of firstChar up one
            lastChar--; // Move position of lastChar down one and repeat loop
        }
    }
    cout << "After :" << target << endl; // Print out end result.
}

void main()
{
    reverse("Test"); //Expect output to be 'tseT'
}
Run Code Online (Sandbox Code Playgroud)

我已经多次调试调试器,但每次它都temp = *firstChar在while循环中的线路周围崩溃.它冻结在这里,导致程序停止运行,无法完成.有什么我只是忽略或有更深层次的东西,为什么我不能这样做.

编辑:有一个其他条件,但我为了简洁起见删除了它.它是在if声明之后,它只是提示单词是1个字符或没有单词.

Pra*_*ian 8

问题不在于reverse函数,而在于调用代码.

reverse("Test");
Run Code Online (Sandbox Code Playgroud)

字符串文字是只读的,尝试修改一个字符串会导致未定义的行为.注意编译器警告(或者如果你没有得到任何警告级别).线之上应当从产生关于一个弃用转换警告const char *char *执行.

要修复代码:

int main() // <-- note the return type, int NOT void!
{
  char str[] = "Test";
  reverse( str );
}
Run Code Online (Sandbox Code Playgroud)