字符串反向实现的问题

Problems with string reverse implementation

本文关键字:问题 实现 字符串      更新时间:2023-10-16

可能的重复项:
为什么这个 C 代码会导致分段错误?

我正在编写一个简单的字符串反向脚本。

我添加了打印语句进行调试。 我在错误 1 之前不断收到运行时异常。 但我似乎想不通原因。

这是我的代码:

#include <iostream>
#include <cstdlib>
using namespace std;
int strlen(char* s){ 
  int i = 0;
  while(*s != ''){
    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;
}

这是我的输出:

            Hello world
            11
            Error0

这个

char* s = "Hello world";

需要

char s[] = "Hello world";

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