递归C中的指针 [英] Pointers in C with recursion

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

问题描述

我通常用Java编程,最近正在看一些C代码. 我遇到了这个程序,但我不知道该指针如何工作. 我知道指针存储了该地址,但几乎无法通过该程序存储该地址. 请告诉输出结果如何为8?

I usually program in java and recently watching some c codes. I came up across this program and I don't know how this pointer thing is working. I know pointer stores the address and all but couldn't make it through the program. Please tell how is the output coming as 8 ?

#include <stdio.h>

int fun(int n, int * f_p) {
    int t, f;
    if (n <= 1) {
      *f_p = 1;
      return 1;
    }
    t = fun(n - 1, f_p);
    f = t + *f_p;
    *f_p = t;
    return f;
}

int main() {
    int x = 15;
    printf("%d\n", fun(5, &x));
    return 0;
}

推荐答案

这里提供的是一个递归函数,用于计算斐波那契数列的第i个元素(从0索引).每次递归迭代都会返回两个值:第i个斐波那契数和第(i-1)个(先前)斐波那契数.由于C语言中的函数只能返回一个值(当然,除非使用结构作为返回类型),否则另一个值(以前的斐波那契数)将通过指针参数f_p返回给调用者.

What you have here is a recursive function that calculates the i-th element of a Fibonacci sequence (indexing from 0). Each recursive iteration returns two values: the i-th Fibonacci number and the (i-1)-th (previous) Fibonacci number. Since a function in C can only return one value (well, unless you use a struct as return type), the other value - the previous Fibonacci number - is returned to the caller through a pointer parameter f_p.

因此,当您调用fun(5, &x)时,该函数将返回8,这是第5个斐波那契数,并且还将5放入x,这是前一个(第4个) )斐波那契数.

So, when you call fun(5, &x), the function will return 8, which is the 5-th Fibonacci number, and it will also place 5 into x, which is the previous (4-th) Fibonacci number.

请注意,x的初始值无关紧要. 15在此程序中不起作用.显然,它以红色鲱鱼的形式存在.

Note that the initial value of x does not matter. That 15 does not play any role in this program. Apparently it is there as a red herring.

如果您知道斐波那契数列是什么,则知道该序列的下一个元素是前两个元素的总和.这就是为什么编写函数以将序列的两个元素返回"给调用者的原因.您可能不在乎顶级调用程序中的先前值(即main中的值),但是嵌套的递归调用确实需要它来计算下一个数字.其余的非常简单.

If you know what a Fibonacci sequence is, you know that the next element of the sequence is the sum of the two previous elements. This is why the function is written to "return" two elements of the sequence to the caller. You might not care about that previous value in the top-level caller (i.e in main), but the nested recursive calls do need it to calculate the next number. The rest is pretty straightforward.

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

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