简体   繁体   English

使用递归打印反向字符串

[英]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. 但是,如果我将reverse(str + 1)更改为reverse(++ str),则不会输出第一个字符。

In: Geeks 在:极客

Out: skee 出: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. 在第一种情况下,str + 1,str根本没有被修改,因此最后一个printf仅打印第一个字符。

Keep in mind that the prefix and postfix ++ actually change the value of the variable. 请记住,前缀和后缀++实际上会更改变量的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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