跟踪C中的递归 [英] Tracing Recursion in C

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

问题描述

我对递归函数和跟踪有基本的了解,但是当我尝试跟踪以下程序时,事情变得有些混乱:

I have a basic understanding of recursive functions and tracing, but something is going haywire when I try to trace the following program:

#include <stdio.h>
#include <stdlib.h>

int f1(int *a, int c);

int main(void) {
    int a=2, b=3, c=4, d=5;
    a = f1(&c, f1(&b,d));
    printf("a= %d b= %d c= %d d= %d\n",a,b,c,d);

    system("pause");
    return 0;
}

int f1(int *a, int c) {
    *a = c - 2;
    c = c*2 - (*a);
    printf("a= %d c= %d\n", *a, c);
    return c - *a;
}

当我跟踪时,我收到两个对f,f(4,4)和f(3,5)的调用.我可以在f函数中正确跟踪返回值和printf语句.但是当我写完它时,main中的最后一个printf给我a = 4 b = 3 c = 2 d = 5我最终以c = 4 ...甚至在我仔细检查了我的工作之后也是如此.当我调试时,我找不到主"c"的值何时发生变化,并且我当然在主"c"的代码中看不到任何算术.

When I trace, I get two calls to f, f(4,4) and f(3,5). I can trace the return values correctly and the printf statement in the f function. But the final printf in main gives me a= 4 b= 3 c= 2 d= 5 when I write it out I end up with c=4... even after I have double and triple checked my work. When I debug I cant find when the value of the main "c" changes and I certainly dont see any arithmetic in the code for main's "c".

预先感谢...我有一种感觉,我忽略了它.

Thanks in advance... I have a feeling its something small that I'm overlooking.

推荐答案

尝试如下:

#include <stdio.h>
#include <stdlib.h>

int f1(int *a, int c, const char *sa);

int main(void) {
    int a=2, b=3, c=4, d=5;
    a = f1(&c, f1(&b,d, "main.b"), "main.c");
    printf("a= %d b= %d c= %d d= %d\n",a,b,c,d);

    system("pause");
    return 0;
}

int f1(int *a, int c, const char *sa) {
  printf("%d: set %s from %d to %d\n", __LINE__, sa, *a, c - 2); 
  *a = c - 2;
  c = c*2 - (*a);
  printf("a= %d c= %d\n", *a, c); 
  return c - *a; 
}

输出

16: set main.b from 3 to 3
a= 3 c= 7
16: set main.c from 4 to 2
a= 2 c= 6
a= 4 b= 3 c= 2 d= 5

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

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