how to read and undestand 3d and 4d arrays?

The data in three-dimensional arrays are stored much like the data in two-dimensional
arrays – in one “long line” of slots for data. If a three-dimensional array is declared as:
int three d[4][5][6];
which data slot (counting from zero) in the “long line” represents three d[2][4][1]?

If you were to write a function that takes a three-dimensional array as a parameter, which of the
three dimensions do you think need to be known by the function? What about a four-dimensional
array?
If int d[4][5][6]; is equivalent to int q[4*5*6];,
then d[2][4][1] is equivalent to q[2*(5*6)+4*(6)+1]

You have to think recursively about this:
Let's see how we get the address of an element in an array. Let's take sometype d[4]; void* ptr = d;

The first element will be at ptr+0,

the second will be at ptr+sizeof(sometype),

nth element will be at ptr+n*sizeof(sometype).


Now imagine that sometype is an array. Then d will be defined as anothertype d[4][5];.

Nothing really changed, d[n] is still at ptr+n*sizeof(sometype),

however now we know that sizeof(sometype) = 5*sizeof(anothertype).

We can rewrite d[n] as ptr+n*5*sizeof(anothertype).

d[n] is an array, so we can apply [m] on it and get (d[n])[m] = addressof(d[n])+m*sizeof(anothertype).

If you paste in the address of d[n], you get d[n][m] = ptr+n*5*sizeof(anothertype)+m*sizeof(anothertype)


Now you should see what happens if anothertype is also an array.

Remember that in C++ pointer arithmetic multiplies by the size of the element for you (I used a void* to bypass this), so you don't need all those "*sizeof". They were there to show that arrays of integers are not that different from arrays of arrays.

To pass a 3d array you'd write a function void foo(int bar[][5][6]). Notice that my conversion form d[][][] to q[] only involved the same two dimensions.
Topic archived. No new replies allowed.