运行时错误反转字符串
Run time error reverse a string
我知道返回结束是不正确的,我正在考虑使用我的一个指针去结束,然后通过字符串的大小返回反向字符串。有没有更有效的方法?还有,更重要的是,我在这里得到一个运行时错误吗?http://ideone.com/IzvhmW
#include <iostream>
#include <string>
using namespace std;
string Reverse(char * word)
{
char *end = word;
while(*end)
++end;
--end;
char tem;
while(word < end) {
tem = *word;
*word = *end;
*end = tem; //debug indicated the error at this line
++word;
--end;
}
return end;
}
int main(int argc, char * argv[]) {
string s = Reverse("piegh");
cout << s << endl;
return 0;
}
将"piegh"传递给Reverse,它被转换为指向char的指针。指向char的指针指向一个只读字符串字面值。也许你想在赋值之前复制字符串字面量"piegh":
char fubar[] = "piegh";
string s = Reverse(fubar);
毕竟,你怎么能证明"piegh"[0] = "peigh"[4];
?
这部分代码是做什么的?while(*end)
++end; //Assuming you are moving your pointer to hold the last character but not sure y
--end;
//y这个while(word < end)
//我也不知道这是如何工作的
这段代码的作用和目的相同
char* StrReverse(char* str)
{
int i, j, len;
char temp;
char *ptr=NULL;
i=j=len=temp=0;
len=strlen(str);
ptr=malloc(sizeof(char)*(len+1));
ptr=strcpy(ptr,str);
for (i=0, j=len-1; i<=j; i++, j--)
{
temp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=temp;
}
return ptr;
}
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何修复我的字符串以避免运行时错误?
- 字符串::插入产生运行时错误
- 为什么此代码使用带有字符串(C )的MAP具有运行时错误
- C++:将字符串流转换为 char* 运行时错误
- 在VC2010中使用Char数组显示字符串时发生运行时错误
- 使用字符串向量初始值设定项时,我收到运行时错误"terminate called after throwing instance of `std::length_error`"
- 为每个使用内部字符串时运行时错误
- 反向字符串脚本给出运行时错误
- C++ 中的运行时错误字符串声明
- 字符串程序C++运行时错误
- 打印字符串时出现运行时错误,即使它在函数中运行良好
- 函数从字符串转换为int时出现运行时错误
- 使用 cout 打印字符串时C++代码块中的运行时错误<<
- 当使用字符串时,c++程序给出一个运行时错误
- c++ char*转字符串运行时错误
- c++运行时错误中的字符串
- 运行时错误反转字符串