Having a brain-fart about 2-D arrays

Started by
10 comments, last by Servant of the Lord 10 years, 11 months ago

Think of the first number as the row and the second as the column. I don't know what you mean about X and Y in relation to the array, typically x is across though (X is a cross, geddit!!!) and y is up or down.

So a foo[1][20] array would be 1 row and 2 columns. May as well just be a 2D array in that case...

You can think of a 3D array as going into or out of the page. You can't visualise a 4D or higher dimensional array.

I'm pretty sure [1][20] is 1 row and 20 columns.

Advertisement

Here's what I was taught to remember:

lets say C:

const int width= 10;
const int height = 10;

int * array_[ width - 1 * height - 1 ] ;

It's just (width * height).

An array that is 10 by 10 equals 100 cells. That's width * height (10 * 10 = 100).

If you subtract one from the width and height, that's 9 * 9 which is 81, which is an access violation for any row above 8.

Also, the order of mathematics (which C and C++ mostly follow) has multiplication resolved before subtraction.

So your code:
width - 1 * height - 1

Actually becomes:
width + (-1 * height) - 1

Which is -1 (You can try it out here).


int cur_index = ( x_ * width ) + y_ ;


This should be (Y * Width) + X.

This works for any number of dimensions:
1D: Index = X
2D: Index = (Y * Width) + X
3D: Index = (Z * (Width * Height)) +  (Y * Width) + X
4D: Index = (T * (Width * Height * Depth)) + (Z * (Width * Height)) +  (Y * Width) + X

This topic is closed to new replies.

Advertisement