Loop through array of unknown size C++

Mike B picture Mike B · Feb 27, 2015 · Viewed 10k times · Source

I am trying to traverse a double array of an unknown size.

Why does the following not work?

for (unsigned int = 1; i < sizeof(anArray)/sizeof(double); i++) {
    ...
}

Everything compiles fine (g++ -Wall -Werror -std=c++11 app.cpp -o app), but the program simply does not even enter the loop.

Full function:

struct stock_data {
   int sell_index;
   int buy_index;
   double profit;
};

stock_data max_profit(double price_array[]) {
   int sell_index = -1, buy_index = -1, 
      min = 0;

   double profit = 0.0;

   for(int i = 1; i < size; i++) {

      if(price_array[i] - price_array[min] > profit) {
         sell_index = min;
         buy_index = i;
         profit = price_array[i] - price_array[min];
      }

      if(price_array[i] < price_array[min]) {
        min = i;
      }
   }  

   return {sell_index, buy_index, profit};
}

int main() {
   double yesterday[] = {0.1, 0.2, 0.3, 0.4};
   stock_data data = max_profit(yesterday);
   cout << data.profit << endl;
}

Answer

Vlad from Moscow picture Vlad from Moscow · Feb 27, 2015

In C++ operator sizeof is a compile-time operator. That is its value is calculated by the compiler not at run-time.

So if as you say the array has unknown size then the compiler can not calculate the size of the memory occupied by the array.

So it is evident that anArray is pointer to first element of the array that you might pass to the function.

Thus this expression

sizeof(anArray)/sizeof(double)

is equivalent to expression

sizeof( double * )/sizeof( double ).

You have to pass also the size of the array explicitly to the function.

Take into account that an array passed by value to a function is converted to pointer to its first element.

Or the other approach is to use conteiner std::vector<double>instead of the arrays.

You could declare your function like

stock_data max_profit(double price_array[], size_t size );

and call it like

 stock_data data = max_profit( yesterday, 
                               sizeof( yesterday ) / sizeof( *yesterday ) );