Multidimensional arrays are defined in much the same manner as one-dimensional arrays, except that a separate pair of square brackets is required for each subscript.Thus, a two dimensional array will require two pair of square brackets, a three-dimensional array will require three pair of square brackets, and so on.
In general terms a multidimensional array definition can be written as
storage-class data-type array[expression 1][expression 2].....[expression n]
where storage-class refers to the storage class of the array, data-type is its data type, array is the array name, and expression 1, expression 2,......,expression n are positive valued integer expressions that indicate the number of array elements associated with each subscript.Remember that the storage-class is optional ;the default values are automatic for arrays that are defined inside of a function, and external for arrays defined outside of a function.
Consider the following two dimensional array definition.
int values[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
Note that the value can be thought of a table having 3 rows and 4 columns (4 elements per row).Since initial values are assigned by rows (i.e. last subscript increasing most rapidly), the results of this initial assignments are as follows.
values[0][0] = 1 values[0][1] = 2 values[0][2] = 3 values[0][3] = 4
values[1][0] = 5 values[1][1] = 6 values[1][2] = 7 values[1][3] = 8
values[2][0] = 9 values[2][1] = 10 values[2][2] = 11 values[2][3] = 12
Remember the first subscript ranges from 0 to 2, and the second subscript ranges from 0 to 3.
Now consider the following three dimensional array definition.
int t[10][20][30] = {
{ /*table 1*/
{1, 2, 3, 4}, /*row 1*/
{5, 6, 7, 8}, /*row 2*/
{9, 10, 11, 12} /*row 3*/
},
{ /*table 2*/
{21, 22, 23, 24}, /*row 1*/
{25, 26, 27, 28}, /*row 2*/
{29, 30, 31, 32} /*row 3*/
}
}
Think of this array as a collection of 10 tables, each having 20 rows and 30 columns.The groups of initial values will result in the assignment of the following nonzero values in the first two tables.
t[0][0][0] = 1 t[0][0][1] = 2 t[0][0][2] = 3 t[0][0][3] = 4
t[0][1][0] = 5 t[0][1][1] = 6 t[0][1][2] = 7 t[0][1][3] = 8
t[0][2][0] = 9 t[0][2][1] = 10 t[0][2][2] = 11 t[0][2][3] = 12
t[1][0][0] = 21 t[0][0][1] = 22 t[0][0][2] = 23 t[0][0][3] = 24
t[1][1][0] = 25 t[0][1][1] = 26 t[0][1][2] = 27 t[0][1][3] = 28
t[1][2][0] = 29 t[0][2][1] = 30 t[0][2][2] = 31 t[0][2][3] = 32
All of the remaining array will be assigned zeros.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment