使用递归反转C中的字符串 [英] Reversing string in C using recursion

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

问题描述

谁能帮我理解这个字符串反转是如何工作的?

Can anyone help me understand how this string reversing works ?

#include <stdio.h>
void reverse();

int main()
{
    printf("Enter a sentence: ");
    reverse();

    return 0;
}

void reverse()
{
    char c;
    scanf("%c", &c);

    if( c != '\n')
    {
        reverse();
        printf("%c",c);
    }
}

在这段代码中,函数 reverse 能够一次获取一个字符的输入句子,对吧?如果它不是 '\n' 它再次调用反向函数.所以下次取第二个字符时,第二个字符将在变量 c 中,对吗?

In this code the function reverse is capable of getting the input sentence one character at a time, right ? And if it is not '\n' it calls the reverse function again. so the next time when the second character is taken, the second character will be in variable c, right ?

如果是这样,这段代码如何能够反转给定的任何字符串?c 中的最终值是多少?

If so, how is this code able to reverse any string that is given ? And what will be the final value in c ?

推荐答案

理解这一点的关键是 char c 变量是函数的local.这意味着每次进入函数时都会在堆栈上分配它.在第二次和后续调用 new 变量的实例被创建在堆栈上.这些都是独一无二的,不会相互干扰.

The key to understanding this is that the char c variable is local to the function. That means that it is allocated on the stack each time the function is entered. On the second and subsequent calls new instances of the variable are created on the stack. These are unique and do not interfere with one-another.

当最终看到终止符 \n 时,函数返回到调用后的行,堆栈恢复到调用函数之前的状态.这意味着变量 char c 将恢复到它以前的值.因此,堆栈将展开,字符以输入的相反顺序打印.

When the terminating character \n is finally seen the function returns to the line after it was called and the stack is restored to the state that it had before the function was called. This means that the variable char c will be restored to it's previous value. The stack is therefore unwound with the characters being printed in reverse order of entry.

一旦 reverse() 返回到 main()c 就会没有 最终值,因为包含它的堆栈帧将被销毁.

Once reverse() returns to main() there will be no final value for c because the stack frame that contained it will have been destroyed.

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

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