C++ Pointer Arithmetic with Array Indices

Ansif
1 min readSep 26, 2023
#include <iostream>
using namespace std;

int main()
{
int arr[] = {1, 2, 3, 4, 5};
int* p = arr;
p += 4;
cout << *p << " ";
p -= 2;
cout << *p;

return 0;
}

Answer: 5 3

Explanation:

  • In this C++ code, an integer array arr is declared and initialized with values from 1 to 5.
  • A pointer p is declared and initialized to point to the first element of the arr array.
  • p += 4; increments the pointer p by 4 positions, causing it to point to the fifth element of the array, which is 5.
  • cout << *p << " "; prints the value pointed to by p, which is 5. So, the first output is "5 ".
  • p -= 2; then decrements the pointer p by 2 positions, moving it back to point to the third element of the array, which is 3.
  • cout << *p; prints the updated value pointed to by p, which is now 3. So, the final output is "3".

This code demonstrates how pointer arithmetic can be used to navigate through an array by adding and subtracting indices from the pointer.

--

--