开发者

String reverse error

开发者 https://www.devze.com 2023-04-12 04:32 出处:网络
Can anyone explain to m开发者_如何学运维e why im getting a \".exe has encountered a problem and needs close\"error, it compiles and works sometimes when i fiddle with the char array, but when it does

Can anyone explain to m开发者_如何学运维e why im getting a ".exe has encountered a problem and needs close"error, it compiles and works sometimes when i fiddle with the char array, but when it does work i sometimes get strange characters at the end of the string.

    #include <iostream>
using namespace std;
char* StrReverse3(char*);
char* StrReverse3(char* str)
{
    char *p;

    int length=0,start=0,end=0;
    length=strlen(str);

    for(start=0,end=length-1;end>= 0,start<=length-1;end--,start++)
    {
        p[start]=str[end];
    }   


    return p;
}
int main()
{
  char str[100]="Saw my reflection in snow covered hills";
  StrReverse3(str);

cin.get();
return 0;
}


You are not initializing p. It's an uninitialized pointer that you are writing to.

Since you are writing this in C++, not C, I'd suggest using std::string and std::reverse:

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string str = "Saw my reflection in snow covered hills";
    std::reverse(str.begin(), str.end());
    std::cout << str;
    return 0;
}

Output:

sllih derevoc wons ni noitcelfer ym waS

See it working online at ideone


char *p; is never initialized, yet p[start] is used as the destination of an assignment. Don't you get compiler warnings from this? I'm amazed it even "works sometimes".


You are accessing memory that wasn't allocated by your program (p can point anywhere!). This is the reason for the problems you have.

I strongly encourage you to

  • read into the topic of dynamically allocating memory with new and delete to understand a very important topic
  • read into the standard template library, especially std::string. You should not use raw pointers like char*, always use standard types when possible.


#include <iostream>
#include <cstring>

using namespace std;

char* StrReverse3(char* str){
    int length=0,start=0,end=0;
    length=strlen(str);

    for(start=0,end=length-1;end > start;end--,start++){
        char temp;
        temp = str[start];
        str[start]=str[end];
        str[end]=temp;
    }

    return str;
}
int main(){
  char str[100]="Saw my reflection in snow covered hills";
  cout << StrReverse3(str);
  cin.get();
  return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号