8 - Double-Subscripted Array
8 - Double-Subscripted Array
What is a 2D array?
The two dimensional or double-subscripted array can be represented as a table with rows and columns.
In other words, a double-subscripted array is used when data is represented using a table. It requires two
subscripts to identify a particular element. By convention, the first subscript identifies the element’s row
and the second identifies the element’s column.
dataType arrayName[rowSize][columnSize];
For example, to declare a 2D integer array table of three rows and 4 columns:
int table[3][4];
To illustrate:
Initializing a 2D Array
Similar to a single-subscripted array, the initializer assigns the elements to its proper location. If lacking,
the rest is initialized to 0. Thus, 0 is assigned to index [0][0] and the rest until index [2][3] is assigned 0.
2. int table[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
The elements are assigned per row. If the row is full, assignment proceeds to the next row and so on.
3. int table[3][4] = {1,2,3,4,5,6,7,8,9,10};
Similar to the first example, if the initializer list has lesser elements, the remaining elements will be 0.
4. int table[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
Since the initializer list is grouped per row, if a row lacks an element, 0 will be assigned to the remaining
elements in that row.
Accessing Elements of the 2D Array
For example,
table[0][0] = 6;
printf(“%d”,table[2][1]);
2. Using a nested-loop
For example,
for(row=0;row<3; row++){
for(col=0;col<4;col++)
printf(“%d”,table[row][col]);
By convention, in accessing elements in a 2D array, nested-loop is used. The outer loop is the row counter
while the inner loop is the column counter.
When a 2D array is passed to functions, the size of the column is required. The reference to the first
element is passed as an actual parameter.
Here is an example: