Two Dimensional (2dim) Arrays

 

Sometimes we refer to it as table (Arrays of Arrays or matrix in mathematics) ,consists of both rows and columns .

 

For example , the array of numbers:

7 66 5 45
9 1 56 2
7 6 4 1

 

is a 2 dim array of integers , it consists of 3 rows and 4 columns .

 

Declaration

 

 datatype   array_name   [#rows][#cols];

 

The first index stands for the number of rows while the second stands for the column .

 

Example

    int vals[3][4];

 

Initialization

 

    int grades[2][3] = { {98 , 88 ,99 },

                                     {100,90,97}};

 

We can omit the inner braces.

 

The separation of the initial values into rows in the declaration is not necessary since the compiler assigns values starting with the [0][0] element and proceeds row by row to fill in the remaining values.

 

    int grades[2][3] = {  98 , 88 ,99,100,90,97 };

 

Is equally valid but does not clearly illustrate to another programmer where one row ends and another begins.

 

If there are not enough initializers for a given a row , the remaining elements of that row are initialized to zeros.

 

 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } },
array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 },
array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
array1 1 2 3
4 5 6
array2 1 2 3
4 5 0
array3 1 2 0
4 0 0

Access

Usually in 2 dim array we use nested loops to access all the elements in the array. We can start looping with rows first and columns second or vise versa.

 

for example

      int r, c;                                        //for rows and columns
for(r = 0; r < 2; r++)
        for(c = 0; c < 3; c++)
              grades[c][r] = 10 * r + c;

0

1

2

10

11

12

 


 

Passing

 

 Passing two dim arrays into functions is a process identical to passing 1 dim array .The called function receives access to the entire array.

 

Column Size

 

We can omit the row size in initialization and in the function call.

 

Why the column size must be included whereas the row size is optional ?

Individual array element is obtained by adding an offset to the starting location of the array.

 

Offset =  Number of bytes in a complete Row  +  Col * Bytes

            =  RowNum * Bytes * ArrayColSize + ColNum * Bytes

IN GENERAL

Location = RowNum  * ArrayColSize + ColNum   

 

For example

Assume integer size =2 Bytes

    Offset for grades[1][1]  = 1*2*3 + 1*2 = 6+2 =8

Or in general :

 Location =  Row(1) * ArrayColSize(2) + ColNum(1 )

                   =2+1=3