Reputation: 63
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.
Upvotes: 0
Views: 313
Reputation: 110658
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;
Upvotes: 12