Understanding and Analyzing Pointer Manipulation in C++
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;
}cout << *p << " ";: This line prints the value pointed to byp, which is the first element of the array, i.e.,1.p--;: This line decrements the pointerpto point to an unspecified memory location before the start of the array. Reading from this memory location yields an arbitrary value, which is32766in this case.cout << *p << " ";: This line prints the value pointed to byp, which is the arbitrary value32766.*p++;: This line is equivalent to*(p++). It increments the pointerpafter dereferencing it, but the result is not used in the output, so it has no effect on the printed value.cout << *p << " ";: This line prints the value pointed to by the incrementedp, which is1again.*p--;: This line is equivalent to*(p--). It decrements the pointerpafter dereferencing it, but the result is not used in the output, so it has no effect on the printed value.cout << *p;: This line prints the value pointed to by the decrementedp, which is32766again.
Let me know if the above analysis is correct. Welcome all comments :)
