简体   繁体   中英

Print reverse of a string using recursion

This code works:

 void reverse(char *str)
{
   if(*str) 
   {
   reverse(str+1);
   printf("%c", *str);
  }
}

But, if i change reverse(str+1) with reverse(++str), it doesn't print first character.

In: Geeks

Out: skee
I don't know why.

Because you're altering the pointer given to you in the very first call of the method, so when it finally gets around to printing itself out and completing the execution, the index has already been incremented to the second character.

In the first case, str+1, str isn't being modified at all, so the very last printf just prints the first character.

Keep in mind that the prefix and postfix ++ actually change the value of the variable.

++str先递增然后打印,您需要str++

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