Oct 24, 2014 at 2:50pm UTC
I am not sure why your code doesn't work, but I rewrote it as so and it works this way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include<iostream>
using namespace std;
int arysum(int *, int );
int main()
{
int const size = 9;
int ary[size] = { 33, 55, 77, 99, 88, 66, 44, 22, 11 };
int sum;
sum = arysum(ary, size);
cout << sum << endl;
return 0;
}
int arysum(int *p, int size)
{
int sum = 0;
if (size == 1)
{
cout << *p << endl;
return *p;
}
cout << *p << endl;
sum = *p;
++p;
--size;
sum += arysum(p, size);
return sum;
}
The reason it wasn't working has something to do with your arguments in
sum = *p + arysum(++p, --size);
Last edited on Oct 24, 2014 at 2:51pm UTC
Oct 24, 2014 at 3:07pm UTC
Thanks for the help! I will rewrite it like that.
Oct 24, 2014 at 3:42pm UTC
sum = *p + arysum(++p, --size);
I suspect undefined behavior (but I have not traced it to prove it).
I doubt there is a required order for the evaluation among *p, ++p, and the call to arysum. So which value of p is used for *p.
The rewrite eliminates any ambiguity.