Why doesn't array.Resize(nElements) produce the same result as ArrayResize(array,nElements)?

 

Example:


#include <Arrays\ArrayInt.mqh>

void OnStart()
{
   int         arr1[];
   CArrayInt   arr2;
   int         nElements = 100;
   
   ArrayResize(arr1,nElements);
   arr2.Resize(nElements);
   
   Print("Dynamic Array1 has ",ArraySize(arr1)," elements");
   Print("Object Array2 has ",arr2.Total()," elements"); 
}
/*
RESULT:
   "Dynamic Array1 has 100 elements"
   "Object Array2 has 0 elements"
*/
//+------------------------------------------------------------------+
 
nicholishen:

Example:



I think this may be a bug, although I'm not sure if metaquotes did this by design...

I fixed the issue by making a change on line 169 in the ArrayInt.mqh

//+------------------------------------------------------------------+
//| Resizing (with removal of elements on the right)                 |
//+------------------------------------------------------------------+
bool CArrayInt::Resize(const int size)
  {
   int new_size;
//--- check
   if(size<0)
      return(false);
//--- resize array
   new_size=m_step_resize*(1+size/m_step_resize);
   if(m_data_max!=new_size)
     {
      if((m_data_max=ArrayResize(m_data,new_size))==-1)
        {
         m_data_max=ArraySize(m_data);
         return(false);
        }
     }
   //if(m_data_total>size)
   if(m_data_total != size)
      m_data_total=size;
//--- result
   return(m_data_max==new_size);
  }
 
nicholishen:


I think this may be a bug, although I'm not sure if metaquotes did this by design...

I fixed the issue by making a change on line 169 in the ArrayInt.mqh

Total() returns the number of actual data element not the size of the array. Arrays classes reserve empty elements and resize automatically when needed.

You didn't fix anything you introduced a bug in the class, as the number of elements is only changed if requested size is lower than current elements count.

Use Max() if you want the size of inner array.

Documentation on MQL5: Standard Library / Data Collections / CArray
Documentation on MQL5: Standard Library / Data Collections / CArray
  • www.mql5.com
Standard Library / Data Collections / CArray - Reference on algorithmic/automated trading language for MetaTrader 5
 
Alain Verleyen:

Total() returns the number of actual data element not the size of the array. Arrays classes reserve empty elements and resize automatically when needed.

You didn't fix anything you introduced a bug in the class, as the number of elements is only changed if requested size is lower than current elements count.

Use Max() if you want the size of inner array.

Thank you!
Reason: