-4

"Write a function that takes a string (character pointer) as input and returns the string reversed. The function should reverse the string in place and return it as the return value of the function."

char *strrev(char *str) {
    char* end = str;
    char tmp = 0;

    if(str) {
        while(*end) {
            end++;
        }

        --end;

        while(end > str) {
            tmp = *end;
            *end-- = *str;
            *str++ = tmp;
        }
    }
}

I am new to C++. I am facing difficulty with this. Can you please correct my code.

Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
user3479279
  • 1
  • 1
  • 3
  • The answer already exists on stackoverflow here http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c – str14821 Apr 19 '14 at 21:41

3 Answers3

3

Here's one for fun:

You will NOT want to turn this in as your assignment :/

See it Live On Coliru

#include <string>

std::string rev(std::string x)
{
    auto a=x.begin();
    auto b=x.rbegin(); 

    while (a<b.base())
        std::swap(*a++, *b++);

    return x;
}

#include <iostream>
int main()
{
    std::cout << rev("") << "\n";
    std::cout << rev("1") << "\n";
    std::cout << rev("12") << "\n";
    std::cout << rev("123") << "\n";
    std::cout << rev("Hello world!") << "\n";
}

Output:

 
1
21
321
!dlrow olleH
sehe
  • 374,641
  • 47
  • 450
  • 633
  • re-inventing `std::reverse` and then after the requirement was "in-place" you take the string by value thereby copying it anyway? – PeterT Apr 19 '14 at 21:54
  • Yes @PeterT, that's what I did. And I did because (a) the algorithm **is** in-place and (b) it makes no sense to return the value if the argument was already updated. (Also, I hope you didn't forget to hold your tongue firmly in the cheek here) – sehe Apr 19 '14 at 22:04
1

So your function, strrev claims to return a char * but it returns... well... nothing. That means that if you use the return value of this function, you're reading some random memory. You're in the realm of undefined behavior at that point and anything goes.

Your compiler should have warned you about this and you should learn to read and understand those warnings - they're there for a reason. If, perchance, it did not warn you, you need to crank up the warnings your compiler generates.

Once you fix your function to return the correct value, it will work as expected. Here's a hint: if you want to reverse the string in place then where would the start of the string be located in memory?

Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
0

There is a standard algorithm in the STL which reverses a range.

char *strrev(char *str) {
    const size_t n = strlen(str);
    std::reverse(str, str+n);
    return str;
}

Or better using C++ strings

void reverse(std::string& s) {
    std::reverse(s.begin(), s.end());
}
Jens
  • 9,058
  • 2
  • 26
  • 43