Array out of range

 

Hi,

array out of range in 'test.mq4' (15,9)

(15,9:   Array[0] = 1.0;   )
void OnStart()
{
   double Array[];
   ArrayResize(Array, 3);
   Array[0] = 1.0;
   Array[1] = 1.0;
   Array[2] = 4.0;
   double ma = iMAOnArray(Array, 3, 3, 0, MODE_SMA, 0);
   Alert("result = ", ma);
}

Why does it happen?

 
oktaryn: Hi, Why does it happen?

Yes, something seems wrong. I used the following code to check the return value and error code of "ArrayResize", and this is what I got ...

#property strict
void OnStart()
{
   double Array[];
   ResetLastError();
   int nSizeArray = ArrayResize(Array, 3);
   PrintFormat("Size: %d, Error: %d",nSizeArray,_LastError);
   Array[0] = 1.0;
   Array[1] = 1.0;
   Array[2] = 4.0;
   double ma = iMAOnArray(Array, 3, 3, 0, MODE_SMA, 0);
   Alert("result = ", ma);
}
2022.09.26 12:44:24.689 Script TestArray EURUSD,H1: removed
2022.09.26 12:44:24.689 TestArray EURUSD,H1: uninit reason 0
2022.09.26 12:44:24.689 TestArray EURUSD,H1: array out of range in 'TestArray.mq4' (8,9)
2022.09.26 12:44:24.689 TestArray EURUSD,H1: Size: -1, Error: 4029
2022.09.26 12:44:24.689 TestArray EURUSD,H1: initialized
2022.09.26 12:44:24.673 Script (Test)\TestArray EURUSD,H1: loaded successfully

4029

ERR_ARRAY_INVALID

Invalid array

However, if I then move the array declaration to the global scope, it then works ...

#property strict
double Array[];
void OnStart()
{
   ResetLastError();
   int nSizeArray = ArrayResize(Array, 3);
   PrintFormat("Size: %d, Error: %d",nSizeArray,_LastError);
   Array[0] = 1.0;
   Array[1] = 1.0;
   Array[2] = 4.0;
   double ma = iMAOnArray(Array, 3, 3, 0, MODE_SMA, 0);
   Alert("result = ", ma);
}
2022.09.26 12:51:31.420 Script TestArray EURUSD,H1: removed
2022.09.26 12:51:31.420 TestArray EURUSD,H1: uninit reason 0
2022.09.26 12:51:31.420 TestArray EURUSD,H1: Alert: result = 2.0
2022.09.26 12:51:31.420 TestArray EURUSD,H1: Size: 3, Error: 0
2022.09.26 12:51:31.420 TestArray EURUSD,H1: initialized
2022.09.26 12:51:31.404 Script (Test)\TestArray EURUSD,H1: loaded successfully

For some reason, it is not considering a locally scoped dynamic array as being dynamic.

I also tested the same concept on MetaTrader 5 and it worked correctly as expected, but it does not work in MetaTrader 4.

This seems to be a MQL4 bug.

EDIT: These tests were on MT4 Build 1356 (5th May 2022).

 

I also confirm on Build 1353.

I didn't know that there is a 1356.

 
Keith Watford #: I didn't know that there is a 1356.

It was pushed out by my broker back then, probably as a bug-fix to something they requested.