字符串反向实现的问题
Problems with string reverse implementation
可能的重复项:
为什么这个 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";
您的原始人正在尝试更改不允许更改的常量内存,因此您需要分配空间并使用字符串对其进行初始化
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在用于格式4的arm模拟器中实现功能时的一个问题
- C++头文件和类实现出现问题
- 类继承,ENUM 与 AST 类实现的问题
- std::max() 函数与定点实现的比较中的问题
- 尝试从头开始实现Leetcode的FizzBuzz多线程问题。收到"libc++abi.dylib: terminating"错误
- 在我的四叉树实现中遇到问题
- 涉及指针和手动实现的矩阵类的问题
- 有关邻接矩阵实现的问题
- 在 C++ 中实现简单链表时出现问题,没有输出
- 基于 SFINAE 的特征实现问题与函数模板重载
- MCS 锁定实现的问题
- 在C++中实现类似 python "map"函数的问题:调用类成员函数
- 在我自己的堆栈中实现top的问题
- 关于C++从派生类调用在基类中实现的虚拟函数的问题
- C++中链表实现的问题
- c++在实现模板化嵌套类时遇到问题
- 简单的最大除数问题 c++ 实现抛出时间限制已超出
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 虚拟 CTOR 的克隆函数实现是否有问题