out of array range problem

 

hey guys and girls, I've got a small problem in this code:


//---- checking number of bars

   if (rates_total < MPeriod - 1 + begin)

    return(0);

   

   //---- declare the local variables = >  HERE THE PROBLEM 

   int first, bar,i=ArraySize(ExtLineBuffer); 

   ExtLineBuffer[i]=1;

   double Sum, SMA;

   

   //---- calculation of starting index

   if (prev_calculated == 0)

    { 

     first =MPeriod - 1 + begin; 



     if(begin > 0)

      PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, begin + MPeriod);

    }

   else first = prev_calculated - 1;



   //---- indicator main loop

   for(bar = first; bar < rates_total; bar++)

    {

     Sum = 0.0;

     //---- price summation

     for(i = 0; i < MPeriod; i++)

      Sum += price[bar - i]; // Sum = Sum + price[bar - iii];

     

     //---- calculation of average price

     SMA = Sum / MPeriod;

     

     //---- filling the buffer with calculated value

     ExtLineBuffer[bar] = SMA;

    }


MY METATRADE LEAD THE OUT OF ARRAY

 


I believe you need to make this change:


//---- declare the local variables = >  HERE THE PROBLEM 

   int first, bar,i=ArraySize(ExtLineBuffer); 

   ExtLineBuffer[i-1]=1;

   double Sum, SMA;


Arrays are 0..n not 1..n, so ArraySize -1 is the max index value.

Hope it helps.

 

Hi astrocypher,

your astro instruments has not told you that code should be shown as code by using either Alt+s or the icon </> from the editor line?

And they missed to let you know that arrays - as long as they have not a fix size - has to be set by ArraySize().

instead of looking into the night sky start reading the docs - for the beginning place in the editor the cursor on a MQ-function and press F1.

;)

 
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum (2019)
              Messages Editor

  2.    for(bar = first; bar < rates_total; bar++){
         Sum = 0.0;
    
         //---- price summation
         for(i = 0; i < MPeriod; i++)
    
          Sum += price[bar - i];
          ⋮
    
         ExtLineBuffer[bar] = SMA;

    Buffers default to as-series. Don't know about your array price. Your for loop is non-series. See ArraySetAsSeries

  3.  if (prev_calculated == 0){ 
         first =MPeriod - 1 + begin; 
        }
       else first = prev_calculated - 1;

    See How to do your lookbacks correctly #9#14 & #19.

Reason: