Two – dimensional array elements can also be referred using pointers, the way one – dimensional array elements referred. The C language treats parts of arrays. Matrices are best example of two – dimensional array. More specifically, each row of two – dimensional array can be thought of as one – dimensional array. Thus, in the following declaration
int mat [3] [4];
can be thought of as three one – dimensional array each containing four elements. Then an one – dimensional array element can be referred using single subscript. If mat is a one – dimensional array, the first element is referred as mat [0], the next element as mat [1] and so on.
Program – Accessing two – dimensional array
#include<stdio.h>
#include<conio.h>
void main ()
{
int mat [3] [4] = {
{10, 15, 20, 25},
{30, 35, 40, 45},
{50, 55, 60, 65},
};
int i;
clrscr ();
for (i = 0; i<3; i++)
printf (“value of mat [%d] is %u\n”, i, mat[i]);
getch ();
}
Output
Value of mat [0] is 6684104
Value of mat [1] is 6684112
Value of mat [2] is 6684120
In this program, whenever the statement
Printf (“value of mat [i] is u\n”, mat[i]);
is executed, it is expected that the value of the 1st one – dimensional array will be displayed. But we know that only specifying the array name; we will get the base address of the array. So in this program the base addresses of all three one – dimensional arrays have been displayed.
The arrangement of elements of two – dimensional array is shown in figure.
Once a two dimensional array is declared, the array name will be referred to the address of the first element of the array. Hence, the expression (mat+0) will refer the address of the first element of the array. So *(mat+0) should refer to the value of the first element. But the first element of the two – dimensional array is a one – dimensional array and mentioning a one – dimensional array we get its base address. Hence referring to (mat + 0) gives us the base address of the first one – dimensional array. So referring to *(mat +0) +0 gives us the address of the first element of the first one – dimensional array, *(mat +0) +1 gives us the address of the second element of the first one – dimensional array, and so on. Hence by referring, *(*(mat + 0) +0) gives us the value of the first element of the first one – dimensional array, whereas *(*(mat + 0) +1) gives us the value of the second element of the first one – dimensional array, and so on. So in general, we can represent mat [i] [j [ ] is equivalent to *(*(mat +1) +j).
About the Author
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc