C pointer to array element

Pointer to array in C : Pointer pointing to the array of elements

  1. Array and Pointer are backbones of the C Programming language
  2. Pointer and array , both are closely related 
  3. We know that array name without subscript points to first element in an array

Example :  One dimensional array

int a[10]; 
Here a , a[0] both are identical

Example : Two dimensional Array

int a[10][10];
Here a , a[0][0] both are identical

Let
  1. x is an array , 
  2. i is subscript variable
            x [ i ]   =  * ( x + i )
                       =  * ( i + x )

                       =   i [ x ]


Proof of the above Formula :

     1 . For first element of array i = 0
                       x[0]  = * ( x + 0) 

                               = *x

Thus we have concluded that , first element of array is equivalent to *x .

     2 . Thus *(x+i) will gives us value of ith element.


Summary :  Consider following code

main()
{
int x[] = {1,2,3,4,5};
int *ptr,i ;
ptr = x
for(i=0;i<5;i++)
{
printf("nAddress : %u",&x[i]);
printf("nElement : %d",x[i]);
printf("nElement : %u",*(x+i));
printf("nElement : %d",i[x]);
printf("nElement : %d",*ptr);
}
}

Output :

Address : 7600
Element : 1
Element : 1
Element : 1
Element : 1
Address : 7602
Element : 2
Element : 2
Element : 2
Element : 2
Address : 7604
Element : 3
Element : 3
Element : 3
Element : 3
Address : 7606
Element : 4
Element : 4
Element : 4
Element : 4
Address : 7608
Element : 5
Element : 5
Element : 5
Element : 5
Following 4 are considered as Equivalent
x[i] *(x + i)
i[x] *ptr

2-D Array can be accessed -

           x [ i ][ j ] = *(x[i] + j)

                          = *( * ( x + i ) + j )


Bookmark & Share