C++ 字符串反向实现的问题

C++ 字符串反向实现的问题,c++,C++,可能重复: 我正在写一个简单的字符串反转脚本 我添加了打印语句以进行调试。在Error1之前,我一直收到运行时异常。但我似乎不明白原因 这是我的密码: #include <iostream> #include <cstdlib> using namespace std; int strlen(char* s){ int i = 0; while(*s != '\0'){ i++; s++; } return i; } void r

可能重复:

我正在写一个简单的字符串反转脚本

我添加了打印语句以进行调试。在Error1之前,我一直收到运行时异常。但我似乎不明白原因

这是我的密码:

#include <iostream>
#include <cstdlib>

using namespace std;

int strlen(char* s){ 
  int i = 0;
  while(*s != '\0'){
    i++;
    s++;
  }
  return i;
}

void reverse(char* src){

  char* dest = src+strlen(src)-1;
  char temp;

  while(src < dest){
    temp = *src;
    cout << "Error0" << endl;
    *src = *dest;
    cout << "Error1" << endl;
    *dest = temp;
    cout << "Error2" << endl;
    src++;
    dest--;
  }

}

int main (void){

  char* s = "Hello world";
  cout << s << endl;
  int i = strlen(s);
  cout << i << endl;
  reverse(s);
  cout << s << endl;

  getchar();
  return 0;
}
这个

需要

char s[] = "Hello world";
您的原始文件试图更改不允许更改的常量内存,因此您需要分配空间并使用字符串初始化它

需要

char s[] = "Hello world";

您的原始文件试图更改不允许更改的常量内存,因此您需要分配空间并使用字符串对其进行初始化。

字符串文字不是
char*
,但由于旧的C详细信息,编译器无论如何都必须接受这一点。对任何字符串文字使用
const char*
,或者可以从文字初始化
char s[]
数组。相同的问题、相同的函数、相同的错误字符串文字不是
char*
,但由于旧的C详细信息,编译器无论如何都必须接受这一点。对任何字符串文字使用
const char*
,或者可以从文字初始化
char s[]
数组。相同的问题,相同的函数,相同的错误
char s[] = "Hello world";