Two dimensional array in c


  • Two dimensional arrays are also called table or matrix, two dimensional arrays have two subscripts.
  • Two dimensional array inwhich elements are stored column by column is called as column major matrix.
  • Two dimensional array in which elements are stored row by row is called as row majo rmatrix.
  • First subscript denotes number of rows and second subscript denotes the number of columns.
  • The simplest form of the Multi Dimensionl Array is the Two Dimensionl Array. A Multi Dimensionl Array is essence a list of One Dimensionl Arrays.

Two dimensional arrays can be declared as follows :

     int int_array[10] ;         // A normal one dimensional array
     int int_array2d[10][10] ;   // A two dimensional array

Initializing a Two Dimensional Array

    Two-dimensional array can be initialized as follows.

     int array[2][2] = {{ 1, 2} , {3, 4}} ;

    Here, in this example, the elements of two rows and two columns are initialized. The internal pairs of braces are not obligatory. The same array can be initialized as under.

    Program:

     #include <stdio.h>
     void printarr(int a[][]);
     void printdetail(int a[][]);
     void print_usingptr(int a[][]);
     main()
     {
      int a[3][2]; \ A
       for(int i = 0;i<3;i++)
         for(int j=0;j<2 ;j++)
         {
           {
             a[i]=i;
           }
        }
      printdetail(a);
     }
     void printarr(int a[][])
     {
      for(int i = 0;i<3;i++)
         for(int j=0;j<2;j++)
         {
           {
              printf("value in array %d,a[i][j]);
           }
         }
     }
     void printdetail(int a[][])
     {
      for(int i = 0;i<3;i++)
         for(int j=0;j<2;j++)
         {
            {
               printf( "value in array %d and address is %8u, a[i][j],&a[i][j]);
            }
         }
     }
     void print_usingptr(int a[][])
     {
        int *b; \ B
        b=a; \ C
        for(int i = 0;i<6;i++) \ D
        {
           printf("value in array %d and address is %16lu,*b,b);
           b++; // increase by 2 bytes \ E
        }
     }

Explanation:

  • Statement A declares a two-dimensional array of the size 3 × 2.
  • The size of the array is 3 × 2, or 6.
  • Each array element is accessed using two subscripts.
  • You can use two for loops to access the array. Since i is used for accessing a row, the outer loop prints elements row-wise, that is, for each value of i, all the column values areprinted.
  • You can access the element of the array by using a pointer.
  • Statement B assigns the base address of the array to the pointer.
  • The for loop at statement C increments the pointer and prints the value that is pointed to by the pointer. The number of iterations done by the for loop, 6, is equal to the array.
  • Using the output, you can verify that C is using row measure form for storing a twodimensional array.