Teemo Teemo - 25 days ago 7
C Question

C recursion return 2 values

I am trying to return sums of digits of 2 numbers using recursion. I think my algorithm is OK, but I am not so good with pointers and I don't understand why they are showing weird values (like when variable is not declared) when they point to variables declared in

main
and they are
0
.

Here is my code:

int get_sums(int **fp, int **sp, int n1, int n2) {
printf("fp: %d\n", fp);
printf("sp: %d\n", sp);
printf("n1: %d\n", n1);
printf("n2: %d\n", n2);

if (n1 == 0) {
return 0;
}

*fp += (n1 % 10);
*sp += (n2 % 10);

return get_sums(&fp, &sp, n1 / 10, n2 / 10);
}

int main(void) {
int f = 0, s = 0;
int *fp = &f;
int *sp = &s;
int first = 123, second = 456;

get_sums(&fp, &sp, first, second);
printf("First sum: %d\nSecond sum: %d\n", *fp, *sp);
return 0;
}

Answer

You have multiple problems:

  • you are using 2 levels of indirection where one would suffice

  • you do not dereference the pointers to pass the values to printf

  • you should just pass the pointers recursively instead of their addresses, but invoke the function with the addresses of the results.

  • you should recurse until both numbers are completely decimated

  • you should enable more warnings for the compiler to help you avoid such mistakes: gcc -Wall for example.

Here is a corrected version:

#include <stdio.h>

void get_sums(int *fp, int *sp, int n1, int n2) {
    printf("fp: %d\n", *fp);
    printf("sp: %d\n", *sp);
    printf("n1: %d\n", n1);
    printf("n2: %d\n", n2);

    if (n1 == 0 && n2 == 0) {
        return;
    }

    *fp += n1 % 10;
    *sp += n2 % 10;

    get_sums(fp, sp, n1 / 10, n2 / 10);
}

int main(void) {
    int f = 0, s = 0;
    int first = 123, second = 456;

    get_sums(&f, &s, first, second);
    printf("First sum: %d\nSecond sum: %d\n", f, s);
    return 0;
}