Ways to store Array address in Pointer

Ways to  store Array address in Pointer



Suppose we have a pointer 'p' and an array 'a'  :


Declaration :



int a[5];
int *p;




Method 1: 

In this we Simply initialize the pointer p with a and in this the a contains the address of a[0].
So we don't  need to write Address of Operator (&).

p=a;




Method 2: 

In this we Directly storing the address of first location in p.

p=&a[0];



Method 3: 

In this method array  'a' which is of integer type contain
base address and in that adding a number gives the address of that
particular location number. 

p=a + 2;


In this p stores the address of a[2].



How it internally works Internally :

Suppose a[0] address is 1001 and for integer we require 4 byte
then for p=a+2

Step 1   a + 2
Step 2  1001 + (4*2)
Step 3  1001 + 8
Step 4  1009

and so p contains the address of a[2] i.e 1009

Method 4: 

p=a;
*(p+4)=40;

by this first we stored base address in p and then we store a value 40 in a[4] 


Conclusion: 

Pointer and arrays support the same set of operations with same meaning for both. The operations with same meaning for both. The main difference beign that pointers can be assigned new addresses while arrays cannot.
Previous
Next Post »