我知道递归步骤应该简化表达式,但在这种情况下,我无法看到它是如何做到的。不应该增加"& sPtr [1]"通过使用"& sPtr [i ++]"并进行适当的修改,直到达到基本情况?
// recursively outputs characters in string in reverse order
void reverse( const char * const sPtr )
{
// if end of the string
if ( '\0' == sPtr[ 0 ] ) { // base case
return;
} // end if
else { // if not end of the string
reverse(&sPtr[1]);// recursion step
putchar( sPtr[ 0 ] ); // use putchar to display character
} // end else
} // end function reverse
答案 0 :(得分:6)
请注意,putchar调用是在反向调用之后。因此,反向函数将调用自身,直到它命中null终止符,然后以相反的顺序调用putchar调用。
按顺序调用堆栈:
reverse( &sPtr[1] )
每次代码传递字符串时,它都不会真正传递整个字符串,而只是指向它的指针。所以:reverse( sPtr+1 )
与index.js
相同,代码只是将指针传递给从下一个字符开始的字符串。