简体   繁体   中英

Reverse String Function C++

I can't understand how the stringReverse function works

Can anyone expalain it to me ???

actually (( stringReverse( &strArray[ 1 ] ); )) is vague.

#include <iostream>

using namespace std;

void stringReverse( const char [] );

int main()
{
const int SIZE = 30;
char strArray[ SIZE ] = "Print this string backwards.";

for ( int loop = 0; loop < SIZE; ++loop )
cout << strArray[ loop ];

cout << '\n';
stringReverse( strArray );
cout << endl;

return 0;
}

void stringReverse( const char strArray[] )
{
if ( strArray[ 0 ] == '\0' )
return;

stringReverse( &strArray[ 1 ] );
cout << strArray[ 0 ];
}

It's actually pretty simple, if you write it out on a piece of paper, using a short string (eg "123" ). Calling stringReverse with an argument of "123" leads to the following calls:

stringReverse("123")
  -> stringReverse("23")
       -> stringReverse("3")
            -> stringReverse("")
               // strArray[0] == 0
               -> return
          cout << '3'
      cout << '2'
cout << '1'

The function recursively calls itself, advancing the current character pointer by one character on each call, until it reaches the end, where it returns immediately. What's left is the output ( cout ) of the recursive calls, that hasn't run yet.

In other words: Each recursive call places a character on a stack. Once the end is reached, and the final recursive call returns, the functions pick up where they left off (after the recursive call), printing the characters from the top of the stack to the bottom.

is simple recursive algorithm, wich go to the end of massive fo chars and when goes back it print char symbols

stringReverse( &strArray[ 1 ] )

is an entery point to next recusion level, where you look at strArray[1] as first element with index 0 (strArray[0]), next recursion at strArray[2], etc.

&strArray

is a link to memory of array, so if you want understand recursive algorithms works from "back" to "begin"

When you pass an array to a function, the array decays to a pointer to its first element (unless you pass it by reference, which is not the case here). In the case of strArray , which is an array of chars, it means that you pass the address of the first letter. So when the main() function calls stringReverse( strArray ); , what it does is passing a pointer to the 'P' of "Print this string backwards." . But remember that a string terminator character ( '\\0' ) is automatically added at the end of every string, so in this case there's one more "invisible" character that marks the end of the array.

The function checks if the first character it has received is '\\0' , and if it isn't so, it recursively calls itself, but this time it doesn't pass the full string as argument; instead, it passes the address of the character at position 1 (remember that array indices start from 0, so it is effectively the second character; in this case, 'r' ). This means that the new string that is passed is "rint this string backwards." . Then it's "int this string backwards." , and it goes on and on, every time skipping the first letter. When there is only the dot '.' (and, as usual, the invisible '\\0' at the end), the next call passes only the '\\0' character, the if is true and the function returns without doing anything. This is what ends the recursion: this time the function doesn't call itself.

Now, the key to recursion is that the program remembers the state at which each function was called, so that when the function is finished, it resumes from there. Which means that the next instruction in the function is the one after stringReverse( &strArray[ 1 ] ); , that is, cout << strArray[ 0 ]; , which prints the first character of the string. Of that string, that is, the substring that was passed that time. In this case, the string was "." (plus the string terminator), so the first character is the dot '.' , and it is printed. The function returns, and the execution of the program resumes from the calling function: the one for which the string was "s." . In that case, strArray[ 0 ] corresponds to the 's' , and it is printed. Then the function returns, the previous one is resumed, and for that the string was "ds." , so 'd' is printed. And it goes all the way back.

This way, characters are printed backwards. This goes on until the end: after the 'P' is printed, the function terminates and the execution returns to main() .

To make an example: take some friends and ask them to form a row. To each of them you give the same instructions: when you receive a ball, remember the string that is given to you, tell the guy on your right the string from the second letter and give him the ball. If the string you are told is empty, do nothing and give the ball back, to the one on the left. When someone gets the ball back, he has to say the first letter (the one he hasn't sent to the others) and give the ball back to the one on the left. So it would be like this:

The first one receives the string "Print this string backwards.", he says "rint this string backwards." to the one on his right and gives him the ball. The second hears "rint this string backwards.", so he says "int this string backwards." and passes the ball to the one on the right. It goes on until the end: the last one receives the ball but the string is empty, so he just gives the ball back to the one on the left. At that point, the guy before him says '.' and gives the ball to the one on the left, who will say 's' and give the ball left, and so on, until the first guy of the row receives the ball and says 'P'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM