


A 2D array is a collection of several 1D arrays stored in adjacent memory locations.
int a[][4] = {
{ 10, 13, 24, 35 }
{ 12, 14, 25, 67 }
{ 23, 44, 44 0}
} ; 
If a 2D array is defined and initialized at the same place mentioning its row dimension is optional.

If a nD array is defined and initialized at the same place mentioning its leftmost dimension is optional.

Base address of a 2D array is address of zero^{th} element of the array.

Zeor^{th} element of a 2D of integers is not the zero^{th} integer, but the zero^{th} 1D array.

In a 2D array a[4][5], a as well as *a would fetch the base address. To reach the integer we have to use **a.

All three following expression are same:
a[i][j]
* ( a[i] + j )
* ( * ( a + i ) + j ) 
There are two ways to pass a 2D array to a function.
main( )
{
int a[][4] = {
{ 10, 13, 24, 35 }
{ 12, 14, 25, 67 }
{ 23, 44, 44 0}
} ;
display ( a, 12 ) ; // one way
show ( a, 3, 4 ) ;// another way
}
display ( int *p, int n )
{
int i ;
for ( i = 0 ; i <>
printf ( "%d", * ( p + i ) ) ;
}
show ( int ( *p )[4], int r, int c )
{
int i, j ;
for ( i = 0 ; i <>
{
for ( j = 0 ; j <>
printf ( "%d", * ( * ( p + i ) + j ) ) ;
}
}
What will be the output of the following program
main( )
{
static int a[3][3] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
} ;
static int *ptr[3] = { a[0], a[1], a[2] } ;
int **ptr1 = ptr ;
int i ;
printf ( "\n" ) ;
for ( i = 0 ; i <<= 2 ; i++ )
printf ( "%d ", *ptr[i] ) ;
printf ( "\n" ) ;
for ( i = 0 ; i <<= 2 ; i++ )
printf ( "%d ", *a[i] ) ;
printf ( "\n" ) ;
for ( i = 0 ; i <<= 2 ; i++ )
{
printf ( "%d ", **ptr1 ) ;
ptr1++ ;
}
}
Output
1 4 7
1 4 7
1 4 7
Explanation
ptr[ ] has been declared as an array of pointers containing the base addresses of the three 1D arrays as shown in Figure 1. Once past the declarations, the control reaches the first for loop. In this loop the printf( ) prints the values at addresses stored in ptr[0] , ptr[1] and ptr[2] , which turn out to be 1, 4 and 7.
In the next for loop, the values at base addresses stored in the array a[ ] are printed, which once again turn out to be 1, 4 and 7. The third for loop is also simple. Since ptr1 has been initialised to the base address of the array ptr[ ] , it contains the address 822.
Figure 1.
Therefore *ptr1 would give the value at address 822, i.e 404, and **ptr1 would give the value at address given by *ptr1 , i,e. value at 404, which is 1. On incrementing ptr1 it points to the next location after 822, i.e 824. Therefore next time through the for loop, **ptr1 gives value at 410 (which is obtained through *ptr1 ), i.e. 4. Similarly, last time through the loop, the value 7 gets printed.
0 comments:
Post a Comment