Easy Tutorial
❮ Cpp Signal Handling C Function Time ❯

C++ Pointer to Array

C++ Arrays

You can skip this chapter and come back to it after understanding the concept of C++ pointers.

If you are familiar with the concept of C++ pointers, you can start learning this chapter. The array name is a constant pointer to the first element of the array. Therefore, in the following declaration:

double tutorialproAarray[50];

tutorialproAarray is a pointer to &tutorialproAarray[0], which is the address of the first element of the array tutorialproAarray. Thus, the following snippet assigns the address of the first element of tutorialproAarray to p:

double *p;
double tutorialproAarray[10];

p = tutorialproAarray;

Using the array name as a constant pointer is legal, and vice versa. Therefore, *(tutorialproAarray + 4) is a legal way to access the data in tutorialproAarray[4].

Once you store the address of the first element in p, you can access the array elements using *p, *(p+1), *(p+2), etc. The following example demonstrates these concepts:

Example

#include <iostream>
using namespace std;

int main ()
{
   // Array of 5 double elements
   double tutorialproAarray[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;

   p = tutorialproAarray;

   // Print the values of each element in the array
   cout << "Array values using pointer " << endl; 
   for ( int i = 0; i < 5; i++ )
   {
       cout << "*(p + " << i << ") : ";
       cout << *(p + i) << endl;
   }

   cout << "Array values using tutorialproAarray as address " << endl;
   for ( int i = 0; i < 5; i++ )
   {
       cout << "*(tutorialproAarray + " << i << ") : ";
       cout << *(tutorialproAarray + i) << endl;
   }

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Array values using pointer 
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
Array values using tutorialproAarray as address 
*(tutorialproAarray + 0) : 1000
*(tutorialproAarray + 1) : 2
*(tutorialproAarray + 2) : 3.4
*(tutorialproAarray + 3) : 17
*(tutorialproAarray + 4) : 50

In the above example, p is a pointer to a double, which means it can store the address of a double variable. Once we have the address in p, *p will give the value stored at the corresponding address in p, as demonstrated in the example above.

C++ Arrays

❮ Cpp Signal Handling C Function Time ❯