# How Multi-Dimensional arrays are represented in memory

• 07-31-2010, 09:26 PM
Riaz Ali
How Multi-Dimensional arrays are represented in memory
It is said that memory is single-dimensional, then how multi-dimensional arrays are represented (and manipulated) in memory. Please reply if anyone knows
• 07-31-2010, 09:35 PM
JosAH
Quote:

Originally Posted by Riaz Ali
It is said that memory is single-dimensional, then how multi-dimensional arrays are represented (and manipulated) in memory. Please reply if anyone knows

They say a picture says more than a thousand words, so here goes: given the following two dimensional array:

Code:

`int[][] array= new int[3][4];`
... the jvm builds it up as a bunch of one dimensional arrays:

Code:

```+---+ |  |  +---+---+---+---+ |  ---> |  |  |  |  | |  |  +---+---+---+---+ +---+ |  |  +---+---+---+---+ |  ---> |  |  |  |  | |  |  +---+---+---+---+ +---+ |  |  +---+---+---+---+ |  ---> |  |  |  |  | |  |  +---+---+---+---+ +---+```
As you can see the two dimensional array is just a bunch of one dimensional arrays held together by a so called 'dope vector' (the vertical array on the left). Each slot of that dope vector points to a row of the original array.

kind regards,

Jos
• 08-01-2010, 12:07 AM
Singing Boyo
Otherwise known as an array of arrays. The actual array variable is a handle to an array of other array handles, which are either handles to arrays of the objects or more array handles, and so on...

Which means this is valid :)

Code:

```+---+ |  |  +---+---+---+---+ |  ---> |  |  |  |  | |  |  +---+---+---+---+ +---+ |  |  +---+---+---+ |  ---> |  |  |  | |  |  +---+---+---+ +---+ |  |  +---+---+---+---+ |  ---> |  |  |  |  | |  |  +---+---+---+---+ +---+```
Edit: can't create a 2D array like that using the simple Type[][] array = new Type[xSize][ySize] though. You'd need a for loop to do that.
• 08-01-2010, 09:17 AM
DarrylBurke
Quote:

Originally Posted by Singing Boyo
You'd need a for loop to do that.

Not necessarily. There could just as well be individual assignment statements.

db
• 08-01-2010, 09:25 AM
JosAH
Quote:

Originally Posted by Darryl.Burke
Not necessarily. There could just as well be individual assignment statements.

Even a single initialization of the ragged array/matrix can do it:

Code:

`int[][] array= { {1, 2, 3, 4}, {5, 6, 7}, {8, 9, 10 11}};`
kind regards,

Jos

edit: if you know that sizes and values of the individual arrays at compile time that is ...