How to avoid array out of range error in mql4 indicator
How to avoid array out of range error in mql4 indicator
Loading saved threads...
Sam · External communityPost link
External question — Stack Overflow Stack Exchange
Author: Sam
Original post: https://stackoverflow.com/questions/69362649
License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/
Adaptation: HTML converted to plain text; contact email addresses removed.
How to deal with or handle/avoid the array out of range error here :
for(int i=0; i<=ObjectsTotal()-1; i++)
{
string objName = ObjectName(0,i);
if(StringFind(objName,"Last#")>=0)
{
string tempval= objName;
string temtext= ObjectGetString(0,objName,OBJPROP_TEXT);
StringReplace(tempval,"Last#","");
int tempnum = (int)(tempval);
for(int k=tempnum; k>=tempnum-20; k--)
{
if(
RBuffer1[k] != EMPTY_VALUE)
{
ObjectDelete(0,objName);
DrawText("Last#"+tempnum,Time[tempnum],Low[tempnum],temtext+"_0","Arial",9,clrWhite);
break;
}
else
if(RBuffer2[k] != EMPTY_VALUE)
{
ObjectDelete(0,objName);
DrawText("Last#"+tempnum,Time[tempnum],Low[tempnum],temtext+"_1","Arial",9,clrWhite);
break;
}
}
}
}
I am sure there is something wrong with my logic but cant figure out what exactly , and the indicator works fine on some timeframes but on 2 ,3 timeframes it throws the error array out of range
This is
for(int k=tempnum; k>=tempnum-20; k--)
where I am receiving the error.
Quote
Report
amirfg · External communityPost link
External answer — Stack Overflow Stack Exchange
Author: amirfg
Original post: https://stackoverflow.com/a/69496359
License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/
Adaptation: HTML converted to plain text; contact email addresses removed.
First of all, check the size of "RBuffer1" using "ArraySize":
int iArrSize = ArraySize(RBuffer1);
if (iArrSize >= 20)
{
...
}
more importantly, the array index starts from 0 up to the predefined size (in your case 20 or 21). But you are trying to access the index 20 up to 41. Obviously, you will receive an "Array out of range" error message. Just change your code to something like:
if (RBuffer1[k - 21] != EMPTY_VALUE)
{
...
}
Quote
Report
Post Reply
Checking account access…