Arrays are relatively simple data structures that programmers create much like any other variable: the definition establishes the variable's data type and name. But arrays are also aggregates or containers. When programmers define an array, they must specify its size. The previous section illustrated a one-dimensional array, which is the most simple. But it is possible to create arrays with more than one dimension.
array_type array_name[n1 ][n2 ] ...[nm ] ;
(a)
one-dimensional : looks like a list or vector
two-dimensional : looks like a table
three-dimensional : looks like a box
four or more dimensions : higher dimensional arrays are allowed but are hard to visualize
(b)
Array definitions and dimensions . C++ arrays have one or more dimensions, which affects their "shape."
Each array definition includes the array's name, type (the type of each element), and a dimension list. Each dimension is the size of the corresponding dimension enclosed in square brackets. Although some programming languages allow a comma-separated list of sizes, C++ requires one pair of brackets for each dimension size. The generalized array definition illustrated here has m dimensions, and a total capacity of n1 × n2 × ... × nm
Common array dimensions and their associated shapes.
In practice, most programs only need arrays with one or two dimensions unless they solve a very specialized problem. (As a practicing software engineer, I once used an array with seven dimensions. But I wrote that program in FORTRAN, which doesn't have structures, and used most of the dimensions as substitutes for structure fields.)
int test[10];
A one-dimensional array . The array definition at the top creates a one-dimensional array of 10 integer elements or variables arranged in rows numbered from 0 to 9.
float test_scores[10][4];
A two-dimensional array . The array definition at the top creates a two-dimensional array of float elements or variables arranged as a table with 10 rows and 4 columns. So, the array has space for 10×4 = 40 float elements. Valid row index values are in the range 0 to 9, and valid column indexes are in the range 0 to 3.
double class_score[5][5][5];
A three-dimensional array . The array definition at the top creates a three-dimensional array of double elements or variables arranged as a box or cube, with five elements on a side. So, the array can hold 5×5×5 = 125 double elements. The array illustrated here has an equal number of rows, columns, and layers, which is not a requirement but a limitation of my drawing ability. Similarly, the indexed elements are all on the surface because I can't draw the interior elements clearly.
Back |
Chapter TOC |
Next