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:

In the example below, an array called Arr and a pointer called p are created. pointer p is assigned the address of Arr. The pointer arithmetic and array-style indexing is used to assign all elements of 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:

Consider one 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

5