C++ Tutorial C++ Advanced C++ References

C++ - Pointer to an Array



The concept of arrays is strongly related to pointers. A pointer that points to the beginning of an array can access the array by using either pointer arithmetic or array-style indexing. Pointers and arrays support the same set of operations, with the same meaning for both. The main difference being that pointers can be assigned new addresses, while arrays will always represent the same address blocks.

Example: pointer to an array

In the example below, an array called Arr and a pointer called p are created. Then the pointer p is assigned to Arr which makes it pointing to the beginning of the array i.e, Arr[0]. After that the pointer arithmetic and array-style indexing are used to assign values to all elements of the Arr.

#include <iostream>
using namespace std;
 
int main (){
  int Arr[5];
  int *p;

  p = Arr;       //pointing to Arr[0]
  *p = 100;   
  p++;           //pointing to Arr[1]
  *p=200; 
  p = &Arr[2];   //pointing to Arr[2]
  *p = 300; 
  p = Arr + 3;   //pointing to Arr[3]
  *p = 400; 
  p = Arr;       //pointing to Arr[0]
  *(p+4) = 500;  //assigning Arr[4]

  for (int i = 0; i <= 4; i++){
    cout<<Arr[i]<<"\n"; 
  }
  return 0;
}

The output of the above code will be:

100
200
300
400
500

Example: access array elements using pointers

Consider one more example, where elements of an array are accessed using pointers.

#include <iostream>
using namespace std;

int main (){
  int Arr[3] = {10, 20, 30};
  int *p;

  p = Arr;       //pointing to Arr[0]

  for (int i = 0; i < 3; i++){
    cout<<"(p + "<<i<<") = "<<p+i<<"\n"; 
    cout<<"*(p + "<<i<<") = "<<*(p+i)<<"\n";    
  }
  return 0;
}

The output of the above code will be:

(p + 0) = 0x7ffc5b77586c
*(p + 0) = 10
(p + 1) = 0x7ffc5b775870
*(p + 1) = 20
(p + 2) = 0x7ffc5b775874
*(p + 2) = 30

❮ C++ - Arrays