Why do I get an Index out of Range exception when copying a Byte array into a Struct array? [duplicate]

StackOverflow https://stackoverflow.com/questions/20918812

  •  24-09-2022
  •  | 
  •  

Question

I have the following code for copying the content of a byte array into a struct array. However when I use it I receive an "Index out of range exception". What is wrong?

public struct pix 
{ 
    public byte b; 
    public byte g; 
    public byte r;
};

namespace ConsoleApplication4
{ 
    class Program
    {
       static  byte[] bmp = File.ReadAllBytes("D:\\x.bmp"); 
       static pix[,] img; 
       static void Main(string[] args)
       {
           int wi = 320; 
           int hi = 240; 
           int i=54; 
           img = new pix[wi-1, hi-1];

           Console.Write(bmp.Length-54); 

           for (int y = hi-1; y > 0; y--)
           {
               for (int x = wi-1; x > 0; x--)
               {
                   img[x,y].b = bmp[i]; 
                   img[x,y].g = bmp[i + 1]; 
                   img[x,y].r = bmp[i + 2];

                   i = i + 3; 
               }       
          } 

    }
}
Was it helpful?

Solution

Seems like you have problem with value of i

Your loop actually, reduced from 320/240 and each time you increment i by 3! which start from 54. so looks like it will soon go out of bound of img

for (int y = hi-1; y > 0; y--)
{
    for (int x = wi-1; x > 0; x--)
    {
        i = i + 3;
    }    
}

Also, img allocation change to below.

img = new pix[wi, hi];

OTHER TIPS

You create an array with the lengths wi - 1 and hi - 1

img = new pix[wi-1, hi-1];

Valid indices into this array are 0 - wi-2 and 0 - hi-2 respectively.

You then start your loop at wi-1 and hi-1 thus accessing the array just outside of its bounds. Probably you just want to change your array allocation to new pix[wi, hi]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top