How to declare a Two Dimensional Array of pointers in C?

View Discussion

Improve Article

Save Article

Like Article

A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element.

How to create a 2D array of pointers:

A 2D array of pointers can be created following the way shown below.

int *arr[5][5];        //creating a 2D integer pointer array of 5 rows and 5 columns.

The element of the 2D array is been initialized by assigning the address of some other element.
In the example, we have assigned the address of integer variable ‘n’ in the index (0, 0) of the 2D array of pointers.

int n;                       //declared a variable
arr[0][0] = &n;        //assigned a variable at positon (0, 0)

Below is the implementation of the 2D array of pointers.

C

#include <stdio.h>

  

int main()

{

    int arr1[5][5] = { { 0, 1, 2, 3, 4 },

                       { 2, 3, 4, 5, 6 },

                       { 4, 5, 6, 7, 8 },

                       { 5, 4, 3, 2, 6 },

                       { 2, 5, 4, 3, 1 } };

    int* arr2[5][5];

  

    

    

    

    for (int i = 0; i < 5; i++) {

        for (int j = 0; j < 5; j++) {

            arr2[i][j] = &arr1[i][j];

        }

    }

  

    

    

    printf("The values aren");

    for (int i = 0; i < 5; i++) {

        for (int j = 0; j < 5; j++) {

            printf("%d ", *arr2[i][j]);

        }

        printf("n");

    }

  

    return 0;

}

Output

The values are
0 1 2 3 4 2 3 4 5 6 4 5 6 7 8 5 4 3 2 6 2 5 4 3 1