Tracing Recursion in C

限于喜欢 提交于 2020-06-28 07:01:18

问题


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;
}

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.


回答1:


Try like this:

#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; 
}

Output

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



回答2:


main()'s c is going to change right here:

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

In the outer call to f1, you're passing a pointer to c. In f1, when you assign *a, it updates whatever a was pointing to, which is c.




回答3:


Call a = f1(&c, f1(&b,d)); passed address of c to f1() and in that function the first line

*a = c - 2;

changes the value of c. *a refers to value of c.



来源:https://stackoverflow.com/questions/15331301/tracing-recursion-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!