Defining a 2 dimensional array in C
 

  • Syntax to define an 2 dimensional array in C:

          dataType  arrayName[ dim1 ][dim2 ];              
      
       E.g.:
      
          float A[20][10];
          int   B[4][3];  
      
      

  • Note:

      • C can only define rectangular shaped 2 dimensional arrays     

How is a 2 dimensional array variable stored in memory

  • The elements of a 2 dimensional array in C is placed row-wise in the memory

    Example:

  • The name (= identifier) of the arary is a symbolic constant equal to the start location of the array

Using a 2 dimensional array

Syntax to access array elements of a 2 dim array in C:

    arrayName[ index1 ][ index2 ]       

Example:

 #include <stdio.h>

 int main( int argc, char *argv[] )
 {
    int B[4][3];    // Define a 2-dim array
    int  i, j;


    for (i = 0; i < 4; i++ )
       for (j = 0; j < 3; j++ )
          B[i][j] = i*j; // Access array element B[i][j] 

    for (i = 0; i < 4; i++ )
    {  for (j = 0; j < 3; j++ )
          printf("%d ", B[i][j]); 
       printf("\n");
    }
 }  

DEMO: demo/C/set1/array3.c