#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 thearr
array. p += 4;
increments the pointerp
by 4 positions, causing it to point to the fifth element of the array, which is 5.cout << *p << " ";
prints the value pointed to byp
, which is 5. So, the first output is "5 ".p -= 2;
then decrements the pointerp
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 byp
, 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.