8.12. Jagged ArraysJagged arrays are maintained as arrays of arrays. Unlike rectangular arrays, rows in jagged arrays can be of different lengths. The program in Fig. 8.20 demonstrates the initialization of a jagged array (array1) and the use of nested For...Next loops to traverse the array. Figure 8.20. Initializing a jagged array.
The program declares a jagged array in method Main. The declaration and allocation of the jagged array array1 (line 6) create a jagged array of three arrays (specified by the 2 in the first set of parentheses after keyword Integer). Lines 79 initialize each subarray so that the first subarray contains the values 1 and 2, the second contains the value 3 and the last contains the values 4, 5 and 6. The nested For...Next statements in lines 1420 behave similarly to those that manipulate the rectangular array in Fig. 8.16. However, in a jagged array, the second dimension is actually an index into the one-dimensional array that represents the current row. In the example, the inner For...Next statement (lines 1517) uses GetUpperBound with the argument 0 to determine the number of columns in each row. In this case, we call GetUpperBound on a single rowarray(i). Arrays of more than two dimensions can be traversed using one nested For...Next statement for each dimension. |