As I told you earlier the concept of arrays is very closely related to pointers. Arrays will work faster by using pointers rather than using a subscript. So it is always recommended to access arrays by using pointers. In the last tutorial I gave a brief overview on 2D arrays in C. Today I will discuss the usage of 2D arrays with pointers. This is one of the most complex topics of C programming, so I would like to suggest you to read this tutorial with full concentration.
2D Arrays with Pointers
A 2D array is nothing but a combination of 1D arrays. To prove my point I would like to show you an example.
#include<stdio.h> int main( ) { int s[4][2]={ {542,43}, {154,354}, {432,54}, {435,435} }; int x; for(x=0;x<=3;x++) printf("n Address of %d th 1-D array = %u",x,s[x]); return 0; }
Output
Explanation
- In the beginning I have declared a 2D array with 4 rows and 2 columns and also initialized it. So we can say that this 2D array is a collection of four 1D arrays having 2 elements each.
- After that I have declared integer variable x which will act as a loop counter.
- Now I have started the for loop with one printf() function. Consider carefully the arguments in printf() function. I have given two arguments which are x and s[x].
- As you can see I am only accessing the 2D array with one dimension. So it will give the addresses of only 1D arrays. s[0] will show the address of first element of first 1D array, s[1] will show address of first element of second 1D array and so on.
Access 2D Array Using Pointer Notation
The best way to learn it is through a program.
#include<stdio.h> int main() { int s[4][2]={ { 542, 43 }, { 154, 354 }, { 432, 54 }, { 435, 435 } } ; int x; printf(" %dn",s[2][1]); printf(" It will give you address of 1st element of 3rd 1D array - %u n",s[2]); printf(" It will give you address of 2st element of 3rd 1D array - %u n",s[2]+1); printf(" Value at that address %d n", *(s[2]+1)); printf(" Alternate way of accessing that address %d n",*(*(s+2)+1)); return 0; }
Output