运行时错误反转字符串

Run time error reverse a string

本文关键字:字符串 运行时错误      更新时间:2023-10-16

我知道返回结束是不正确的,我正在考虑使用我的一个指针去结束,然后通过字符串的大小返回反向字符串。有没有更有效的方法?还有,更重要的是,我在这里得到一个运行时错误吗?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;
}