【发布时间】:2017-08-04 00:59:34
【问题描述】:
请知道这个反向函数是如何工作的,不是很明白,我知道指针确实指向字符串[0],但是这个函数如何能够打印正确的字符来正确地反转字符串,这是怎么回事是存档吗?
#include <iostream>
using namespace std;
void reverse(char *s); //prototype
//-------------------------------------------------------------------
int main ()
{
char str[] = "begin_this is a test_last"; //cstring to be reverse
reverse(str); //recursive function
cout << "\n";
return 0;
}
//---------------------------------------------------------------------
void reverse(char *s)
{
if(*s){
reverse(s + 1);
}else
return;
cout << *s; //question how this print the string in reverse??????
}
【问题讨论】:
-
在递归的情况下,C 和 C++ 对于摇滚乐来说已经足够接近了,因此阅读很有帮助:How Recursion works in C
-
这对任何较长的字符串都不起作用。
-
是时候学习调试器了。
-
一个递归堆栈,当它全部展开时会从前打印。刚开始学习时有点难以概念化,但你会做到的。
-
感谢您抽出宝贵时间,但没有太多答案,有点假设,我明白了。