Java Reference
In-Depth Information
Array of int arrays
0
1
2
3
4
...
Array of 10 ints
Array of 10 ints
Figure 12.11: A Multidimensional Array in Java
A[0][0]
A[0][1]
. . . A[1][0]
. . .
A[1][1]
A[9][8]
A[9][9]
Figure 12.12: Array A[10][10] Allocated in Row-Major Order
first assigns to matrix an array object containing five references to integer
arrays. Then, in sequence, five integer arrays (each of size ten) are created,
and assigned to the array matrix references (see Figure 12.11).
Other languages, like C and C
cient
to contain all the elements of the array. The array is arranged in row-major
order , with values in each row contiguous and individual rows placed sequen-
tially (see Figure 12.12). In row-major form, multidimensional arrays really
are arrays of arrays, since in an array reference like A[i][j],thefirstindex(i)
selects the i-th row, and the second index (j) chooses an element within the
selected row.
An alternative to row-major order is column-major order ,whichisused
in Fortran and related languages. In column-major order values in individual
columns are contiguous, and columns are placed adjacent to each other (see
Figure 12.13). Again, the whole array is allocated as a single block of memory.
How are elements of multidimensional arrays accessed? For arrays allo-
cated in row-major order (the most common allocation choice), we can exploit
the fact that multidimensional arrays can be treated as arrays of arrays. In
particular, to compute the address of A[i][j], we first compute the address
of A[i],treatingA as a one-dimensional array of values that happen to be
arrays. Once we have the address of A[i], we then compute the address of
++
, allocate one block of memory, su
. . .
. . . A[0][1]
A[9][9]
A[0][0]
A[8][9]
A[1][0]
A[1][1]
Figure 12.13: Array A[10][10] Allocated in Column-Major Order
 
Search WWH ::




Custom Search