C++ Pointer arithmetic

Pointer arithmetic in C++ refers to the mathematical operations carried out on pointers to enable them to point to various memory locations. Only pointers that point to an array are capable of doing pointer arithmetic. The size of the data type that the pointer points to is taken into account when executing arithmetic operations on it.

Example:

#include <iostream>
using namespace std;

int main() {
   int arr[] = {10, 20, 30, 40, 50};
   int* ptr = arr;

   cout << "The value of the first element of the array is: " << *ptr << endl;
   ptr++;

   cout << "The value of the second element of the array is: " << *ptr << endl;
   ptr++;

   cout << "The value of the third element of the array is: " << *ptr << endl;
   ptr--;

   cout << "The value of the second element of the array is: " << *ptr << endl;
   return 0;
}

Output:

The value of the first element of the array is: 10
The value of the second element of the array is: 20
The value of the third element of the array is: 30
The value of the second element of the array is: 20

A pointer named ptr is declared and initialised in the example above to point to the array’s first element, arr. The dereferencing operator * is then used to output the value of the first element. The third element’s value is written after the pointer is double-incremented to point to it. The second element’s value is written after the pointer is decremented to point back to it. This shows how to traverse an array using pointer arithmetic.