In this article, we are going to learn how to access a 2D array using pointers in C.We have explained in detail by step by step logic to access elements of the array.
Write C program to input and print elements of 2D array using pointers and function
Let us first understand how we access a 2-dimensional array. For example, we have an array 2Darr[3][3].In the below example we have explained how to identify rows and columns by labeling “rows” and “columns”.
Column1 Column2 Column3
Row 0 -> 1 2 3
Row 1 -> 4 5 6
Row 2 -> 7 8 9
In this example, we have explained how to access rows and access columns in a 2D array. This is the pseudocode that we used in the below program.
Accessing Rows
2Darr : Base address of 2Darr array.
*(2Darr + 0) : Base address of row 0 of 2Darr array.Or first element of row 0 address.
*(2Darr + 1) : Base address of row 1 of 2Darr array.Or first element of row 1 address.
*(2Darr + 2) : Base address of row 2 of 2Darr array.Or first element of row 2 address.
Accessing Columns
2Darr : Base address of 2Darr array.
(*2Darr + 0) : Base address of Column 0 of 2Darr array.Or first element of Column 0 address.
(*2Darr + 1) : Base address of Column 1 of 2Darr array.Or first element of Column 1 address.
(*2Darr + 2) : Base address of Column 2 of 2Darr array.Or first element of Column 2 address.
**2Darr : Value at index 2Darr[0][0] of 2Darr array, means 1.
*(*(2Darr + 0) + 0) : Value at index 2Darr[0][0] of 2Darr array, means 1.
*(*(2Darr + 0) + 1) : Value at index 2Darr[0][1] of 2Darr array, means 2.
*(*(2Darr + 0) + 2) : Value at index 2Darr[0][2] of 2Darr array, means 3.
*(*(2Darr + 1) + 0) : Value at index 2Darr[1][0] of 2Darr array, means 4.
*(*(2Darr + 1) + 1) : Value at index 2Darr[1][1] of 2Darr array, means 5.
*(*(2Darr + 1) + 2) : Value at index 2Darr[1][2] of 2Darr array, means 6.
*(*(2Darr + 2) + 0) : Value at index 2Darr[2][0] of 2Darr array, means 7.
*(*(2Darr + 2) + 1) : Value at index 2Darr[2][1] of 2Darr array, means 8.
*(*(2Darr + 2) + 2) : Value at index 2Darr[2][2] of 2Darr array, means 9.
C program to access two dimensional array using pointer
In this example c program, we are accessing elements of the 2D array, to understand this code briefly use the above pseudocode.
#include <stdio.h>
int main()
{
int TwoDarr[3][3];
int i, j;
printf("Please enter the elements of 3x3 2D array (9 elements):\n");
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
scanf("%d", (*(TwoDarr + i) + j));
}
}
printf("The elements of 3x3 2D array are:\n");
for (i = 0; i < 3; i++)
{
printf("Row %d -> ",i);
for (j = 0; j < 3; j++)
{
printf("%d ", *(*(TwoDarr + i) + j));
}
printf("\n");
}
return 0;
}
Output
Please enter the elements of 3x3 2D array (9 elements):
1
2
3
4
5
6
7
8
9
The elements of 3x3 2D array are:
Row 0 -> 1 2 3
Row 1 -> 4 5 6
Row 2 -> 7 8 9