How to declare a Two Dimensional Array of pointers in C?
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 position (0, 0)
Below is the implementation of the 2D array of pointers.
C
#include <stdio.h> // Drivers code 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]; // Initialising each element of the // pointer array with the address of // element present in the other array for ( int i = 0; i < 5; i++) { for ( int j = 0; j < 5; j++) { arr2[i][j] = &arr1[i][j]; } } // Printing the array using // the array of pointers printf ( "The values are\n" ); for ( int i = 0; i < 5; i++) { for ( int j = 0; j < 5; j++) { printf ( "%d " , *arr2[i][j]); } printf ( "\n" ); } return 0; } |
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
A two-dimensional array of pointers can also be created using Dynamic Memory Allocation.
We can use the malloc() function to dynamically allocate memory.
ptr = (cast-type*) malloc(byte-size)
Below is the implementation of a 2D array of pointers using Dynamic Memory Allocation.
C
#include <stdio.h> #include <stdlib.h> // Drivers code 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 } }; // Creating 2D array of pointers using Dynamic Memory // allocation through malloc() function int *** arr2 = malloc (5 * sizeof ( int **)); for ( int i = 0; i < 5; i++) arr2[i] = malloc (5 * sizeof ( int *)); // Initialising each element of the // pointer array with the address of // element present in the other array for ( int i = 0; i < 5; i++) { for ( int j = 0; j < 5; j++) { arr2[i][j] = &arr1[i][j]; } } // Printing the array using // the array of pointers printf ( "The values are\n" ); 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
Please Login to comment...