Search code examples
c++stringcharreversecstring

Reversing a string, weird output c++


Okay, so I'm trying to reverse a C style string in C++ , and I'm coming upon some weird output. Perhaps someone can shed some light?

Here is my code:

 int main(){    

    char str[] = "string";
    int strSize = sizeof(str)/sizeof(char);

    char str2[strSize];

    int n = strSize-1;
    int i =0;


    while (&str+n >= &str){ 
        str2[i] = *(str+n);         
        n--;
        i++;
    }

    int str2size = sizeof(str)/sizeof(char);
    int x;

    for(x=0;x<str2size;x++){
        cout << str2[x];
    }

}

The basic idea here is just making a pointer point to the end of the string, and then reading it in backwards into a new array using pointer arithmetic.

In this particular case, I get an output of: " gnirts" There is an annoying space at the beginning of any output which I'm assuming is the null character? But when I try to get rid of it by decrementing the strSize variable to exclude it, I end up with some other character on the opposite end of the string probably from another memory block.

Any ideas on how to avoid this? PS: (would you guys consider this a good idea of reversing a string?)


Solution

  • A valid string should be terminated by a null character. So you need to keep the null character in its original position (at the end of the string) and only reverse the non-null characters. So you would have something like this:

    str2[strSize - 1] = str[strSize - 1]; // Copy the null at the end of the string
    
    int n = strSize - 2; // Start from the penultimate character