This code is a college assignment. I'm supposed to write a recursive function that will return the largest consecutive sum in an array.
This is what I have so far:
Parameters:
- x = memory adress to the array
- sfm = memory adress to the max suffix sum
- n = size of the array
Returns: maximum consecutive sum of the array
double rsubMax(double *x, double *sfm, int n)
{
n -= 1;
double globalMax;
double auxSfm = 0;
double aux;
if (n == 0)
{
auxSfm = x[n];
globalMax = auxSfm;
}
else
{
aux = rsubMax(x, sfm, n - 1);
auxSfm = *sfm;
if (auxSfm x[n] > aux)
{
auxSfm = x[n];
globalMax = auxSfm;
}
else if (auxSfm x[n] > 0)
{
auxSfm = x[n];
globalMax = aux;
}
else
{
auxSfm = 0;
globalMax = aux;
}
}
*sfm = auxSfm;
return globalMax;
}
When I try to run it on some tests, I get:
Process finished with exit code -1073741571 (0xC00000FD)
I'm not very used to the debugging tool, but when I try to use it, it gives me a segmentation fault on the line right after the first 'else'.
I believe the function's logic is correct. I just barely know anything about memory allocation.
CodePudding user response:
n -= 1;
When you decrease n = 0 will use second branch if like this
aux = rsubMax(x, sfm, -1);
Remove decreasing n, it could help