Pages

Tuesday, November 22, 2016

Fetching elements in multi-dimensional array in C using pointers

As opposed to traditional method of using integer indexes, elements in a multi-dimensional array in C can be fetched using pointers.

Consider the following code using multi-dimensional array.

#include <stdio.h>

int main()
{
 
    int matrix[10][20] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    int i,j;
    for(i = 0; i < 3;i++){
        for(j = 0 ; j< 4 ;j++){
            printf("%d\n",(*(*(matrix +i)) + j));  
        }
    }
 
return 0;
}

Different methods are available to print individual elements from the above array. Three different approaches are described below.

1.  *(a[i] + j) :
    a[i] refers to first element in i th array of matrix. Adding j gives the address of j th element in i th array.
    De-referencing this address gives value at ith row and j th column of matrix array

2. (*(matrix + i))[j]
      *(matrix + i) gives address of first element of i th row of matrix. [j] gives j th column of row i.

3. *(*(matrix + i) + j)
     As above, *(matrix + i) gives address of first element of i th row of matrix. Adding j gives address of j th column of matrix. De-referencing this element gives the value of  i th row and j th column.

No comments:

Post a Comment