Struct Array out of range?

 

Hi, I'm learning how to create struct arrays and so I attempted to replicate the concept from the FileWriteArray() example code in the MQL Reference.

I think my logic seems sound but there may be something I'm overlooking as I'm just learning about structs.  Perhaps my syntax is incorrect?

The intention here is there is a starting count of 0 and every tick it increments +1 so that countArray[0].count = 0, then 1, then 2, etc so that the count itself is always equal to the element number in the array.

I'm getting an error that this Array is out of range. when loading it into the strategy tester.  Anyone have any idea why this is and how to resolve this issue?

Thank you!

struct structure
{
   int count;
};
structure countArray[];
int count = 0;

void OnTick()
  {
      countArray[count].count = count;
      count++;
  }
The Fundamentals of Testing in MetaTrader 5
The Fundamentals of Testing in MetaTrader 5
  • www.mql5.com
The idea of ​​automated trading is appealing by the fact that the trading robot can work non-stop for 24 hours a day, seven days a week. The robot does not get tired, doubtful or scared, it's is totally free from any psychological problems. It is sufficient enough to clearly formalize the trading rules and implement them in the algorithms, and...
 
Hoi Cheng:

Hi, I'm learning how to create struct arrays and so I attempted to replicate the concept from the FileWriteArray() example code in the MQL Reference.

I think my logic seems sound but there may be something I'm overlooking as I'm just learning about structs.  Perhaps my syntax is incorrect?

The intention here is there is a starting count of 0 and every tick it increments +1 so that countArray[0].count = 0, then 1, then 2, etc so that the count itself is always equal to the element number in the array.

I'm getting an error that this Array is out of range. when loading it into the strategy tester.  Anyone have any idea why this is and how to resolve this issue?

Thank you!

Hey,

when using such arrays you need to resize it when you set new elements, or initially set the appropriate size, currently in your code the size is 0, this is why it doesnt work - you are calling an element (in this case 0), which doesnt yet exist

So before you set the new element value, move count to before that line, and after it write 
ArrayResize(countArray,count);
 

brilliant, thank you!  I never knew about this array-resizing business but it makes perfect sense.

In order to make this work, I had to write

ArrayResize(countArray, count+1);

since if countArray[0].count = 0, there is still one element total necessary to store that value in the array.

 
Hoi Cheng:

brilliant, thank you!  I never knew about this array-resizing business but it makes perfect sense.

In order to make this work, I had to write

since if countArray[0].count = 0, there is still one element total necessary to store that value in the array.

Great !