0

I try to reverse a string by pointer walking. Logic is simple that I have two pointers to char one of them head that points to first char of the string. The other tail points to second-last character(before \0) of the string. Swap then char-by-char. C-style it works well, but C++-style doesn't work. I wonder its reason.

C-style

#include <iostream>
#include <cstring>
using std::cin;
using std::cout;
using std::endl;
using std::string;

void reverse(char *str)
{
    char *tail, *head;
    head = &str[0];
    tail = &str[strlen(str)];

    cout << "String inverted is: ";

    while ((head!=tail)&&(head!=--tail))
    {
        char temp=*head;
        *head++=*tail;
        *tail=temp;
    }
}

int main(int argc, char const *argv[])
{
    char str[100];
    cout << "Enter a string: ";
    cin.getline(str,100);
    reverse(str);
    cout << str;
    cout <<"\n";

    return 0;
}

C++-style

#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;

void reverse(string str)
{
    char *tail, *head;
    head = &str[0];
    tail = &str[str.size()];

    cout << "String inverted is: ";

    while ((head!=tail)&&(head!=--tail))
    {
        char temp=*head;
        *head++=*tail;
        *tail=temp;
    }
}

int main(int argc, char const *argv[])
{
    string str;
    cout << "Enter a string: ";
    getline(cin,str);
    reverse(str);
    cout << str;
    cout <<"\n";

    return 0;
}
3
  • 5
    C++ style would be std::reverse(str.begin(), str.end()); Commented Sep 3, 2015 at 12:18
  • 1
    but C++-style doesn't work Care to explain that? Also you should be using iterators to modify the string and not pointers into the strings data. Commented Sep 3, 2015 at 12:18
  • 1
    Because you're passing the string by value. Commented Sep 3, 2015 at 12:20

1 Answer 1

4

You are not passing the string in to reverse by reference. You are currently passing in a copy of the string.

make reverse have this prototype:

void reverse(string& str)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.