I wrote a recursive function that returns the sum of the array when called. This is my code:
#include <iostream>
struct array {
int A[10];
int size;
int length;
};
void displayArray(struct array arr) {
std::cout << "the elements are :-" << std:: endl << '\t';
for (int i = 0; i < arr.length; i ) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
int i = 0;
int sum(int* a, int length) {
// Size of an int element.
int j = 4;
if (i < length) {
return a[i 1] sum((a j), length);
}
else {
return 0;
}
}
int main()
{
struct array arr = {{1,2,3,4,5,6,7}, 10, 7};
int* p;
std::cout<< sum(&arr.A[0],arr.length );
}
However, it is not returning anything and also, I ran it on an online compiler. It is not showing any error or warning, but it's not showing any output either.
CodePudding user response:
well in this
int i = 0;
int sum(int* a, int length) {
int j = 4;
if (i < length) {
//std::cout << a[i];
return a[i] sum((a j), length);
}
}
your exit condition is i >= length
, but you never change i
so this will keep recursing till you run out of stack space. Since this is a very strange function (I mean why is j = 4) I cant suggest a solution, only why it doesnt work at present
here is the error on my dev box
Unhandled exception at 0x00007FF711A9297E in ConsoleApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000003E526B3FA8).
CodePudding user response:
You are running in an endless loop because of your if condition never reaching an end. Besides this, the global i and the local j are both superflous. Maybe it would be easier to use your length to access the array and as an end marker and decrease it with each call of sum
int sum(int* a, int length){
if (--length >= 0)
return a[length] sum(a, length);
else
return 0;
}
by the way, I would recommend using
`std::array <int, 10> a= {1,2,3,4,5,6,7};'
instead of your struct including int A[10];
this gives you out of bounds checking, iterators for your collection, no need for C pointer algorithmics, ...