# How can I convert this 2D pixel array into a 1D pixel array?

I have this 2D array that works like this, and I made this image to help illustrate what my 'Screen' class's array represents.

Basically, the first part [x][] is how many scan-lines there are. And then, [][x] is how many pixels long that particular line is.

Now, I've researched 'flatting 2D arrays' or '2D to 1D array conversion' - and yes, they 'work', but they seem to just break it... What I mean is, have the screen goes a certain color, then crashes by going out of bounds. Then, other times, it just goes out of bounds, and nothing happens.

I've tried the following, which is what caused it to crash:

final int[] PIXEL_BUFFER = game.getPixelBuffer();

int pixel = 0;
for (int j = 0; j < SCANLINE_COUNT; j++)
{
for (int i = 0; i < SCANLINE_LENGTH; i++)
{
PIXEL_BUFFER[pixel] = this.PIXEL_BUFFER[j][i];
pixel++;
}
}


I've searched high and low, but I can't figure this out. If anyone knows how, it'd be greatly appreciated if I could gain some insight. Until then, I'm going to keep trying.

Many thanks.

• What you're doing should work fine assuming that PIXEL_BUFFER has enough memory allocated to hold the same number of elements as this.PIXEL_BUFFER, that you have the correct SCANLINE_COUNT and SCANLINE_LENGTH, and assuming a pixel from this.PIXEL_BUFFER fits into a single int. If any of those assumptions is incorrect, then you will either get too little or too much data. But the approach is correct, so check those assumptions. – user1118321 Mar 7 '18 at 3:38