0

I've seen that these types of array are sometimes seen as a matrix. I had a teacher who said that this was an easy way to look at it, and that the real way it looks is in a linear form. For example:

int a[2][3][2] = {0, 1, 2, 3 , 4, 5, 6, 7 , 8, 9, 10, 11};

How would you represent this in a linear way?

1
  • also see here Commented May 20, 2015 at 16:20

3 Answers 3

4

As far as memory layout is concerned,

int a[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },
                   { { 6, 7 }, { 8, 9 }, { 10, 11 } } };

is the same as:

int b[12] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

and a[i][j][k] is equivalent to b[i * 6 + j * 2 + k].

Sign up to request clarification or add additional context in comments.

Comments

2

For your three-dimensional example, you can use an array b of size 2*3*2 = 12 and access the former element a[i][j][k] via b[k + 2 * ( j + 3* i)].

Alternatively, any other rearrangement will do as well, for example b[i + 2 * ( j + 3* k)]. The optimal choice depends on how you mainly want to traverse the array.


In general, one can translate any array

a[0 ... N_1-1][0 ... N_2-1] ... [0 ... N_k-1]

into a linear array b of size N_1 * N_2 * ... * N_k. In practice, the only thing you have to change is the index function: so when you want to access element a[i_1][i_2] ... [i_k] in your original array, you use the following instead

b[i_k + N_k * ( i_{k-1} + N_{k-1} * ( ... N_2 * i_1) ...))]

Comments

0

An array is a number of elements, stored consecutively in memory.
A 2D array is an array of arrays.
As such, a 2D array is a number of arrays, stored consecutively in memory. It follows that all the elements of the 2D array are stored consecutively in memory.

In your concrete example, the compiler will allocate memory in this structure:

 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
  ------- ------- ------- ------- ------- ---------
   line 0  line 1  line 2  line 3  line 4  line 5
  ----------------------- -------------------------
          block 0                 block 1
  -------------------------------------------------
                      3D array

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.