10.1 Two-Dimensional Arrays
Some problems require the use of a two-dimensional array, which organizes data into rows and columns similar to a table or grid as illustrated in Figure 10.1.1. The individual elements are accessed by specifying two indices, one for the row and one for the column.
The C programming language only provides for the explicit declaration of static 2-D arrays, although, dynamic 2-D arrays are possible. To create a 2-D array, you must specify four pieces of information:
- the name of the array
- the number of rows and columns in the array,
- the type of data stored in each element.
The total number of elements in the 2-D array will be the number of rows multiplied by the number of columns (nrows x ncols). For example, the declaration:
- int table[3][5];
creates a 2-D array with the name table that contains a total of 15 elements arranged into 3 rows of 5 columns each, all of which store integer values.
As with 1-D arrays, a two-dimensional array can only store values of a specific data type and once created, you cannot change the size of the array.
|
Defining a 2-D Array
type name[nrows][ncols];
|
Note that the elements of the array are not initialized to any given value, but will contain the values that are currently stored in the memory location where the array is created. A 2-D array can be initialize when it is first created in a similar fashion to 1-D arrays:
- int data[3][2] = {
- {15, 20},
- {8, 16},
- {23, 7}
- };
which results in the array
|
Defining and Initializing a 2-D Array
type name[nrows][ncols] = { { row-0 values }, { row-1 values }, : };
The initial values of a 2-D array can be specified when it is first created. The values must be provided as a collection of sequences within a pair of curly braces (
{ }).
|
Given the following array declaration
- const int SIZE = 12;
- float table[6][SIZE];
How many rows and columns does the array contain?
- 6 rows and 6 columns
- 6 rows and 12 columns
- 12 rows and 6 columns
- can not be determined