Reversing string

This is a discussion on Reversing string within the C++ Programming forums, part of the General Programming Boards category; Hello,
I have a string say,
"My name is John"
I want to reverse it like,
"yM eman si nhoJ"
...

This is a pointer to a string literal which the address of is passed into your reverse function. The reverse function then accesses and attempts to modify this string literal which is a big no-no. Doing this usually, but not always, causes a program to crash. As a start, you should replace that line of code with the following:

Code:

char text[] = "My name is John";

This makes text an array and not a pointer to a string literal. As an array, you can pass its address to the reverse function and that code can make modifications to the array without a crash... assuming you aren't doing anything else that's unsafe.

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens

A C++ style solution to the first problem would involve reading token by token into a std::string object using the overloaded operator>> for input streams. A C++ style solution to the second problem would involve say, the std::reverse generic algorithm, or something along those lines (possibly written by yourself, since this is presumably for practice).

Note that you can quite easily reverse a string in-place; extra memory proportional to the string length is unnecessary.

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

A C++ style solution to the first problem would involve reading token by token into a std::string object using the overloaded operator>> for input streams. A C++ style solution to the second problem would involve say, the std::reverse generic algorithm, or something along those lines (possibly written by yourself, since this is presumably for practice).

Note that you can quite easily reverse a string in-place; extra memory proportional to the string length is unnecessary.

Hi Lase... I forgot where I was there for a second... just love playing with pointers. If course your advice is better for C++ than mine.