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

Comments

Popular posts from this blog

textcolor in c

wherex in c

traffic light program in c, traffic light simulation