I wrote the following code in Microsoft Visual Studio:
#include <iostream>
using namespace std;
int main()
{
int i = 1;
int *p;
int val;
p = &i;
*p = 101;
val = *(p + 2);
cout << val << endl;
cout << i << endl;
return 0;
}
In the line val = *(p + 2), since *(p + 2) returns the value of the second integer after the one to which p points, and p currently points to the integer 101, I expected val to be of value 101+4×2=109.
When I executed the code in Visual Studio, the output showed the value of variable val was instead a random garbage value. Why was this so?
val = *p + 2? In casepis a pointer to an array, you could simply usep[2](what you're doing now), but here, you don't have an array, so I assume you want the value atpand add2.