Creating Arrays with Pointer
Creating Arrays with pointer:
We have already seen that a pointer can hold the base address returned by new operator while allocating a required chunk of memory space. For eg :
const int * ptr = new int[5];
The above statement will allocate 5 * 2 = 10 bytes contiguously one after another at adjacent locations (memory addresses). The first address out of all,these set of addresses being assigned to pointer ptr. The picture we obtain can be viewed as :
If you observe the whole scenario you will find that directly or indirectly we are getting an array containing 5 members, each of these members having a integer values (int data-type). The base addresses being assigned to the pointer variable ptr itself.
Now we are free to apply the pointer arithmetic to the base pointer ptr to read
and write other locations as well.
The first location is ptr can be referred as (ptr + 0) ie. 8fc4fff4.
The second location can be referred as ( ptr + 1) ie. 8fc4fff6
The third location can be referred as ( ptr + 2) ie. 8fc4fff8
The fourth location can be referred as ( ptr + 3) ie. 8fc4fffa
The fourth location can be referred as ( ptr + 4) ie. 8fc4fffc
Similarly to read and write value at these locations we can readily use (*)
operator i,e.
- ptr i.e. *(ptr +0) // reads/writes value at the address held by ptr i.e. at 8fc4fff4.
- (ptr + 1) //reads writes value at the address held by ptr+1 i,e. at 8fc4fff6.
- (ptr + 2) // reads / writes value at the address held by ptr+2 i,e. at 8fc4fff8.
- (ptr + 3) // reads / writes value at the address held by ptr + 3 i,e. at 8fc4fffa.
- (ptr + 4) // reads / writes value at the address held by ptr i,e. at 8fc4fffc.
Now let’s think the whole process in reverse order. Thinking in reverse manner you find that we have ultimately created a 1-Dimensional Array having 5
elements in it.
Let us proof this by comparing the following two programs :
main ( )
|
main( )
|
Both of the above versions of the programs are equivalent. Thus we can infer that the name of base pointer (ptr) in the second version is acting same as the name
of the array (arr) itself present in the second version.
Note : The name of any array declared in any C++ program, is a pointer to the address of the first element of that array. |
The above two versions can be used in compliment of each other, as and when required. They can also be used in mixed form. So the following expressions are equivalent :
arr[i] Ξ *(arr +i) |
So , following mixed expressions can be used while writing codes using arrays :
main( ) { int MyArray[5] ; //Inputting array elements for(int i = 0 ; i <= 4 ;i++) { cout<< “Input Values : ”; cin>> MyArray[i]; } // Using array notation showing array elements for( i = 0 ; i<= 4 ; i++) { cout<< *(ptr + i) ;// Using Pointer notation } }