0

I am trying to reverse a char array in C++. Here is my code :

void reverse(char s[]);
int main()
{
    char s [] = "Harry";
    cout << reverse(s) << endl;

    system("PAUSE");
    return 0;
}

void reverse(char s[])
{
    if( strlen( s ) > 0 ) {
        char* first = &s[ 0 ];
        char* last = &s[ strlen( s ) - 1 ];
        while( first < last ) {
            char tmp = *first;
            *first = *last;
            *last = tmp;
            ++first;
            --last;
        }
        return;
    }

However, I got an error at cout << reverse(s) << endl; that line which located in main method and I have no idea why.The error message is no operator match these operands. Anybody can help me fix this?

Thanks in advance.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Yvonne
  • 63
  • 1
  • 4
  • 12

1 Answers1

12

Your reverse function has a return type of void. This means it doesn't return anything so your cout << reverse() has nothing to output.

Seems like instead you meant to do:

char s [] = "Harry";
reverse(s);
cout << s << endl;

Alternatively, you can make reverse return a char* and put return s; at the end of its body. However, that would be a little strange, since you're using both the argument and the return value for the same function output. Just use it as above.

Of course, you could do this much more easily if you make use of the standard library; use std::string and std::reverse:

std::string s = "Test";
std::reverse(s.begin(), s.end());
std::cout << s << std::endl;

See it in action.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Oh okay okay thanks alot. I just learnt pointer today and our teacher asks us to write this using pointer. Thanks tho – Yvonne May 10 '13 at 14:03