C++ Pointer to an Array



C++ Pointer to an Array :

#include <iostream>
using namespace std;
 
int main ()
{
   // an array with 5 elements.
   double arr[5] = {10,20,30,40,50};
   double *ptr;

   ptr = arr;
 
   // output each array element's value 
   cout << "Print Array Elements : " << endl; 
   for ( int i = 0; i < 5; i++ )
   {
       cout << "*(ptr + "  << i << ") : ";
       cout <<  *(ptr + i) << endl;
   }

   return 0;
}

Output :

Print Array Elements : 
*(ptr + 0) : 10
*(ptr + 1) : 20
*(ptr + 2) : 30
*(ptr + 3) : 40
*(ptr + 4) : 50

Pictorial representation of the array is shown below –
Array - C++ Programming

Explanation :

  1. In the above example we have printed the elements of the array using the pointer.
  2. Pointer is special type of variable which stores the address of the variable.
  3. The base address of the array is assigned to the pointer variable using following statement.
ptr = arr;

Now consider the program in which we have assigned the starting address of array to pointer variable.

Now we know that starting address of array is nothing but the address of first element

Main Logic behind Calculation :

Consider that we need to calculate the value of *(ptr + 4). It can be evaluated as –

*(ptr + 4) = Value at (ptr + 4)
           = Value at (ptr + 4 * Size of Data Type)
           = Value at (ptr + 4 * 4)
           = Value at (ptr + 16)
           = Value at (1000 + 16)
           = Value at (1016)
           = 50

In the above calculation we have added 4 to pointer variable. Why we multiplied 4 with size of data type ? See Re-commanded article