一种使用C语言中的递归来反转字符串的方法对我来说很奇怪 [英] A way to reverse a string using recursion in C strange to me

查看:77
本文介绍了一种使用C语言中的递归来反转字符串的方法对我来说很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在大学笔记中找到以下代码来反转C中的字符串.我不明白在这个例子中递归是如何工作的,因为对我来说这似乎很神奇!更具体地说,如果我键入单词一个" ,程序将打印出单词"eno" .根据说明,该功能以递归方式从用户读取字符,直到用户按下 Enter('\ n'),然后打印出反转的单词.但是,如果该函数最后一次递归调用自身是在用户按下Enter键之后,如何打印该单词,此后该程序将无法再次进入该函数以调用 printf ?它是否使用某种缓冲区以及它如何工作?这是C源代码:

I found the following code to reverse a string in C in my university notes. I do not understand how the recursion works in this example since it seems magic to me! To be more specific, if I type the word "one" the program prints out the word "eno". According to the explanation, the function reads characters from the user recursively until the user presses Enter('\n') and then prints out the reversed word. But how is it possible to print the word if the last time the function calls itself recursively is when the user presses Enter and after that the program can't get into the function again in order to call the printf? Does it use some kind of buffer and how it works?? Here is the C source code:

#include <stdio.h>

void readCharsAndReverse(void);

int main (void)
{
    printf ("Give characters to reverse:");
    readCharsAndReverse();
    printf ("\n\n");
    system("PAUSE");
}

void readCharsAndReverse(void)
{
    char ch;
    scanf ("%c", &ch);
    if (ch != '\n')
       readCharsAndReverse();
    printf ("%c", ch);
 }  

推荐答案

一旦您输入 Enter ,您的方法 readCharsAndReverse 开始返回,即,首先将打印最后弹出的字符和堆栈上的所有其他递归调用将开始弹出.因此,以相反的顺序逐个打印所有字符.

As soon as you enter Enter, your method readCharsAndReverse starts returning ie., first it will print the last entered character and all other recursive calls on stack start being poped off..thus by printing all the characters one by one in reverse order..

就像您将某些东西放在底部架子上并移到上部架子上做同样的事情一样.当遇到 Enter 时,您将粘贴的东西粘贴在墙上,然后回到下面在墙上粘贴先前粘贴的内容旁边的架子,然后粘贴您保存的所有内容,依此类推.

Its just like you keep something in bottom shelf and move onto upper shelf to do the same thing..and when you encounter Enter you paste whatever you have, on the wall and come back to below shelf and paste whatever you have kept there, on the wall next to previously pasted content, so on..

这篇关于一种使用C语言中的递归来反转字符串的方法对我来说很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆