Structs and references and variables

 

If I have a struct array e.g. MyStruct[] that I access like MyStruct[2]


how can I take MyStruct[2] and put it into a variable maintaing the reference (not copying it)


so that instead of writing.


MyStruct[2].abc = 1;

MyStruct[2].def = 2;


I could write:

st = MyStruct[2]; // <------ does this copy or is it a reference?

st.abc = 1;

st.abc = 2;


also, how do you make a constructor to initialize a struct?


and also, if a struct contains a string - then it is intiialized - what does that mean? all zero'd out? like booleans are false, strings are "" ?, numbers are 0?

 

MQL does not support reference variable (only params) and you cannot use pointers with structs (only classes), so the struct assignment is always a copy. That's why I no longer use structs for anything and only use classes (unless I'm subclassing an MqlStruct to pass to an MqlFunction).

Also, you always need to initialize your members either in the initialization list or in the body of the constructor. 

class MyClass {
public:
   int abc;
   int def;
   MyClass():abc(0), def(0){}
};

now you can use pointers to accomplish your goal

MyClass objs[2];

MyClass *o1 = &objs[0];

o1.abc = 10;

assert o1.abc == objs[0].abc
 
thanks I'll keep that in mind for the future, for me it is simpler just to leave my code as-is but good to know
 

another quick question here, if that's ok:

what's the {0} doing below?

MqlTradeResult res={0};

 

also, if I were to used ZeroMemory() (not sure if this is necessary) on a struct, but my struct contains 2 nested structs.. does that mean I need to do


ZeroMemory(s);

ZeroMemory(s.a);

ZeroMemory(s.b);


or just ZeroMemory(s); ?


or just nothing?