Multi-dimensional Arrays

Array of arrays

 

Declared by use of two or more sequential [square brackets]:

 

data type array Name[array size 1] [array size 2] ;

 

Akin to N rows & columns in a spreadsheet:

Column 0 Column 1 Column 2 Column 3
Row 0 arrayName[ 0 ][ 0 ] arrayName[ 0 ][ 1 ] arrayName[ 0 ][ 2 ] arrayName[ 0 ][ 3 ]
Row 1 arrayName[ 1 ][ 0 ] arrayName[ 1 ][ 1 ] arrayName[ 1 ][ 2 ] arrayName[ 1 ][ 3 ]
Row 2 arrayName[ 2 ][ 0 ] arrayName[ 2 ][ 1 ] arrayName[ 2 ][ 2 ] arrayName[ 2 ][ 3 ]

 

int myMultiArray[ 3 ] [ 4 ;  //declares a  two dimensional array called myMultiArray that contains 6 elements; e.g. in 3 rows / 4 columns

 

Defined by assiging values, separated by a comma, within {curly braces} for each dimension:

 

int myMultiArray[ 3 ] [ 4 ] = { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 } } ; //same as:

int myMultiArray[ 3 ] [ 4 ] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } ; //no need for nested curly braces

 

Single values can be defined by assigning the value to the specific element number, starting from zero for each dimension!

 

myMultiArray[ 2 ] [ 2 ] = 42 ; //sets the element in row 2, column 2 to 42

 

Specific elements can be accessed by assigning an array element to a variable

 

int myVar = myArray[ 1 ] [ 3 ] ; //assigns myVar with the element  contained in row 1, column 3

 

Compile & run:

Element [2][2] is: 10
Element [2][2] is now: 42
myVar has now been assigned the [2][2] element: 42

Leave a Reply