This blog is under construction

Thursday 26 December 2013

Pointer to two dimensional array

If a pointer holds reference to an array, then it is called pointer to an array or array pointer.

How to declare pointer to an array?
int (*ptr)[3][3];
Here, ptr is the pointer to 2d array.

Let us see how to access array elements using pointer to a two dimensional array.


  #include <stdio.h>
  int main() {
        int i, j;
        /* arr is 3 X 3 array */
        int arr[3][3] = {10, 20, 30,
                         40, 50, 60,
                         70, 80, 90};
        int (*ptr)[3][3]; // pointer to 2d array

        /* assigning reference */
        ptr = &arr;

        /* accessing 2d array elements using pointers */
        for (i = 0; i < 3; i++) {
                for (j = 0; j < 3; j++) {
                        printf("%d ", *(*((*ptr) + i) + j));
                }
                printf("\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~$ ./a.out
  10 20 30 
  40 50 60 
  70 80 90 


No comments:

Post a Comment