I have a Simple Moving Average calculating function that I modified slightly. It should get a double array as input, as well as a moving average period integer, and should output another array with the calculated moving average values.
I followed this tutorial on passing arrays to functions and this one on returning arrays from functions. I implemented the practices mentioned there in the code below, most importantly, function returning the address of the output array, where the output array, being a local variable, has to be declared static
within the function body.
When printing out the length of array before the function call, inside the function body, and after function evaluation, I found that the array is still not passed correctly to the function. The output I'm getting is:
Array length before passing to function: 21
Array length after passing to function: 0
Resulting array length: 0
And the code is:
#include <iostream>
using namespace std;
double *sma(double prices[], int MA_Period) {
cout << "Array length after passing to function: " << sizeof(prices)/sizeof(*prices) << "\n";
for(int i=0; i<sizeof(prices)/sizeof(*prices);i++) {
cout << prices[i] << "\n";
}
static double output[sizeof(*prices)];
for(int pos=0; pos<sizeof(prices)/sizeof(*prices); pos++) {
double sum=0;
if(pos<MA_Period) pos=MA_Period;
for(int i=1;i<MA_Period;i++,pos--)
sum+=prices[pos];
while(pos>=0) {
sum+=prices[pos];
output[pos]=sum/MA_Period;
sum-=prices[pos+MA_Period-1];
pos--;
}
}
return output;
}
int main(){
double arr[21] = {1.5,2.2,3.3,4.4,3.1,2.1,3.1,2.7,2.9,3.1,3.3,1.9,2.2,2.0,2.3,2.4,2.8,4.0,3.8,3.2};
cout << "Array length before passing to function: " << sizeof(arr)/sizeof(*arr) << "\n";
double *res = sma(arr, 3);
cout << "Resulting array length: " << sizeof(res)/sizeof(*res) << "\n";
return(0);
}