Wednesday, November 2, 2011

The Real Thing Array in C programming language

If you have grasped the concept of storage of array elements in memory and the arithmetic of pointers, here is some real food for thought. Once again consider the following array.

This is how we would declare the above array in C,

int  num[ ] = { 24, 34, 12, 44, 56, 17 } ;

We also know that on mentioning the name of the array we get its base address. Thus, by saying *num we would be able to refer to the zeroth element of the array, that is, 24. One can easily see that *num and *( num + 0 ) both refer to 24. Similarly, by saying *( num + 1 ) we can refer the first element of the array, that is, 34. In fact, this is what the C compiler does internally. When we say, num[i], the C compiler internally converts it to *( num + i ). This means that all the following notations are same:

num[i] 
*( num + i ) 
*( i + num )
i[num]

And here is a program to prove my point.

/* Accessing array elements in different ways */
main( )
{
      int  num[ ] = { 24, 34, 12, 44, 56, 17 } ;
      int  i ;

      for ( i = 0 ; i <= 5 ; i++ )
 {
            printf ( "\naddress = %u ", &num[i] ) ;
            printf ( "element = %d %d ", num[i], *( num + i ) ) ; 
            printf ( "%d %d", *( i + num ), i[num] ) ;
 }
}

The output of this program would be: 

address = 65512 element = 24 24 24 24
address = 65514 element = 34 34 34 34
address = 65516 element = 12 12 12 12 
address = 65518 element = 44 44 44 44
address = 65520 element = 56 56 56 56
address = 65522 element = 17 17 17 17

No comments:

Post a Comment