i am trying to access an array elements and make some Logic gates operations over it, so basically i am trying to get the neighbors of each element, but i am getting the error, Index was outside the bounds of the array error.. thats one of my conditional if statements, and i know i am trying to access an element which is not exist either less than 0 element position or bigger than or = array.length
if (states[i] == 0 && states[i + 1] == 0)
{
states[i] = 0;
}
any idea how to fix it?
Top comments (6)
If you are intentionally accessing something outside the array, put the code in a try/catch block:
Never attempt to catch an
IndexOutOfRangeException
when using arrays. This exception can be avoided simply by making sure your index is within the range - which in arrays means larger than -1 and smaller than array.Length.For more information, read Eric Lippert's blog post entitled Vexing Exceptions
Nope, it is not intentionally the purpose here is only to check the element neighbors only
I don't get this code. You're setting the array cell to 0 if it is 0 - why?
to check the neighbors of the element in the array
this line
states[i] = 0;
doesn't make sense inside this condition, because you already know that the value instates[i]
is0
.And as for the exception - if you know
i
is smaller than the array's length, it means that i+1 must be equal to the array's length to throw that exception - so, guessing that this i is a for loop variable, you need the loop to stop one step before - sofor(var i = 0; i < arr.Length - 1; i++) {/* do stuff here */}