Home > database >  System out of range in for loop
System out of range in for loop

Time:12-31

System is giving me out of range exception when p = 255. My understanding is that with "OR" operator, later part of if statement should come into affect. However, it is not. Please advise on how to fix it.

for (int p = 0; p < 256; p  )
{
    if (buffer[p] == buffer[p   1] || buffer[p] == buffer[p - 1])
    {
        //Code
    }
}

CodePudding user response:

In the first iteration p = 0; With p = 0; the right side of the conditional expression is trying to access buffer[-1], which throws the Exception.

You should start the iteration with index 1 and end it one item before the last item in the buffer. Try something like this:

for (int p = 1; p < buffer.Length - 1; p  )
{
    if (buffer[p] == buffer[p   1] || buffer[p] == buffer[p - 1])
    {
        //Code
    }
}

CodePudding user response:

You have out of range error. It means that index p is out of buffer range, which is

[0 .. buffer.Length - 1]

Now, let's have a look at index usage: you have

if (buffer[p] == buffer[p   1] || buffer[p] == buffer[p - 1])

add you address

  1. buffer[p] where p can be in 0..buffer.Length - 1 range
  2. buffer[p 1] where p can be in -1..buffer.Length - 2 range
  3. buffer[p - 1] where p can be in 1..buffer.Length range

combining all 3 ranges together we get p in 1..buffer.Length - 2 or

for (int p = 1; p < buffer.Length - 1; p  ) 
  if (buffer[p] == buffer[p   1] || buffer[p] == buffer[p - 1]) {
    ...
  }
  • Related