Let us reiterate the arrangement of array elements in a two-dimensional array of students, which contains roll nos. in one column and the marks in the other.
The array arrangement shown in Figure 8.4 is only conceptually true. This is because memory doesn’t contain rows and columns. In memory whether it is a one-dimensional or a two-dimensional array the array elements are stored in one continuous chain. The arrangement of array elements of a two-dimensional array in memory is shown below:
We know that the expressions s[0] and s[1] would yield the addresses of the zeroth and first one-dimensional array respectively. From Figure 8.6 these addresses turn out to be 65508
and 65512.
and 65512.
Now, we have been able to reach each one-dimensional array. What remains is to be able to refer to individual elements of a one-dimensional array. Suppose we want to refer to the element s[2][1] using pointers. We know (from the above program) that s[2] would give the address 65516, the address of the second one-dimensional array. Obviously ( 65516 + 1 ) would give the address 65518. Or ( s[2] + 1 ) would give the address 65518. And the value at this address can be obtained by using the value at address operator, saying *( s[2] + 1 ). But, we have already studied while learning one-dimensional arrays that num[i] is same as *( num + i ). Similarly, *( s[2] + 1 ) is same as, *( *( s + 2 ) + 1 ). Thus, all the following expressions refer to the same element,
s[2][1]
* ( s[2] + 1 )
* ( * ( s + 2 ) + 1 )
s[2][1]
* ( s[2] + 1 )
* ( * ( s + 2 ) + 1 )
Using these concepts the following program prints out each element of a two-dimensional array using pointer notation.
/* Pointer notation to access 2-D array elements */
main( )
{
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
} ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n" ) ;
for ( j = 0 ; j <= 1 ; j++ )
printf ( "%d ", *( *( s + i ) + j ) ) ;
}
}
And here is the output...
1234 56
1212 33
1434 80
1312 78
/* Pointer notation to access 2-D array elements */
main( )
{
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
} ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n" ) ;
for ( j = 0 ; j <= 1 ; j++ )
printf ( "%d ", *( *( s + i ) + j ) ) ;
}
}
And here is the output...
1234 56
1212 33
1434 80
1312 78
No comments:
Post a Comment