1

I'm trying to print out the result of my returned sum but for some reason it prints out 0, but when I check the sum inside the function its performing its objective correctly. For example if I pass in an array of 10 items each equal to their index (0...9) the sum inside the function is 45 but when I print it out back in main() it prints 0. I'm really confused to say the least.

Here is my function, which I call using:

printf("%d\n", addArray3(arrayA, 9, 0));

To clarify, arrayA is a pointer to an 10 item'd array of integers.

// Sums array using recursion
int addArray3(int (*arrayA)[], int n, int sum){
    if (n<0){
        return sum; 
    } else {
        sum += (*arrayA)[n];
    }
    addArray3(arrayA, --n, sum);
}

If anyone can clear this up I'd really appreciate it, thanks!

1
  • 2
    Surely your compiler gives you a warning when you compile that code. Do not ignore the warnings! Commented Dec 31, 2015 at 6:52

3 Answers 3

2

You are missing a return on the last line. Compile with all the warning on and it might find that for you.

Related question about this behaviour that covers whats going on here (not having a return): Implicit int return value of C function

Sign up to request clarification or add additional context in comments.

Comments

0

Check this modified recursion function with efficient use of pointers:

void addArray3(int *arrayA, int n, int* sum){
    if (n<0){
        return;
    } else {
        *sum += arrayA[n];
    }
    addArray3(arrayA, --n, sum);
}

int main ()
{
    int ar[] = { 1, 2, 3};
    int sum = 0;
    addArray3(ar, 2, &sum);
    printf("%d\n",sum);

    return 0;
}

Comments

-1

Try, like this,it's working for me in both the cases:

1) Storing the return value in int t. OR

2) Directly printing the return value.

#include <stdio.h>

int main()
{
        int a[10] = {0,1,2,3,4,5,6,7,8,9};
        int t;

//      t = addArray3(a,9,0);
//      printf("%d\n",t);
        printf("%d\n",addArray3(a,9,0));
}

int addArray3(int (*arrayA)[], int n, int sum)
{
        if (n<0)
        {
                return sum;
        }
        else
        {
                sum += (*arrayA)[n];
        }
        addArray3(arrayA, --n, sum);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.