0

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);
}
lazarea
  • 1,129
  • 14
  • 43
  • 1
    You can’t use `sizeof` for determining the size of dynamic arrays. It only works for static arrays. A pointer’s size is a pointer’s size – Sami Kuhmonen Mar 28 '21 at 10:20
  • https://stackoverflow.com/questions/8269048/length-of-array-in-function-argument – Retired Ninja Mar 28 '21 at 10:20
  • 1
    The good news is C++ gives you better options that a regular array like `std::vector` and `std::array` which both keep track of their size. – Retired Ninja Mar 28 '21 at 10:23
  • This is my third time today with the same comment, please compile your code with `-Wall`, understand those warnings, and then fix your code. – Zoso Mar 28 '21 at 10:25
  • In the example you linked of passing an array to a function, they passed the size of the array as well as the array itself. You need to do the same. BTW, the second tutorial is giving very bad advice which makes me worry about the quality of the whole tutorial/website. – Galik Mar 28 '21 at 10:28

0 Answers0