Understanding and Analyzing Pointer Manipulation in C++

Ansif Blog
1 min readOct 18, 2023

--

#include <iostream>
using namespace std;

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

return 0;
}
  1. cout << *p << " ";: This line prints the value pointed to by p, which is the first element of the array, i.e., 1.
  2. p--;: This line decrements the pointer p to point to an unspecified memory location before the start of the array. Reading from this memory location yields an arbitrary value, which is 32766 in this case.
  3. cout << *p << " ";: This line prints the value pointed to by p, which is the arbitrary value 32766.
  4. *p++;: This line is equivalent to *(p++). It increments the pointer p after dereferencing it, but the result is not used in the output, so it has no effect on the printed value.
  5. cout << *p << " ";: This line prints the value pointed to by the incremented p, which is 1 again.
  6. *p--;: This line is equivalent to *(p--). It decrements the pointer p after dereferencing it, but the result is not used in the output, so it has no effect on the printed value.
  7. cout << *p;: This line prints the value pointed to by the decremented p, which is 32766 again.

Let me know if the above analysis is correct. Welcome all comments :)

--

--