Search code examples
algorithmic-tradingmql5metatrader5

How can I populate a dynamic two dimensional array in a for loop


This might seem trivial to many but it seems to be getting the better of me as I've not been able to figure out how to use the ArrayResize() (which I believe is very necessary) to solve this.

In the code below I want to populate ar[][2] when isBody is true. How can I achieve this.

int ar[][2];

void CheckBody()   {

   for (int i = 20; i >= 0; i--) {
   
      if (isBody) {
         int a = i + 1;
         int b = i - 3*i;
         
         // how to populate ar with [a,b] when isBody is true in this block
         
      }
   }
}


Solution

  • Try the following code, it's programmed to run as an EA but can easily be modified if used in an indicator (you will have to add your code for the isBody variable).

    #property strict
    
    int ar[][2];
    
    //+------------------------------------------------------------------+
    //| Initialization function of the expert                            |
    //+------------------------------------------------------------------+
    int OnInit()
    {
       ArrayInitialize(ar,NULL);
       ArrayResize(ar,1);
    return(INIT_SUCCEEDED);
    }
    //+------------------------------------------------------------------+
    //| Deinitialization function of the expert                          |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
    
    }
    //+------------------------------------------------------------------+
    //| "Tick" event handler function                                    |
    //+------------------------------------------------------------------+
    void OnTick()
    {
       for(int i=20; i>=0; i--)
       {
          if(isBody)
          {
             if(ar[0][0]!=NULL) ArrayResize(ar,ArrayRange(ar,0)+1);
             int a=i+1;
             int b=i-3*i;
             ar[ArrayRange(ar,0)-1][0]=a; ar[ArrayRange(ar,0)-1][1]=b;
          }
       }
    }