+ 3
Pointers going crazy?
When I use int* p = new int; *p = 32; int pp = *p++; cout<<*p I expect to see output 32 but I get a weird result which varies. Can anyone help describe why this happens?
3 Antworten
+ 7
I think
int pp=*p++;
Is the problem.
It must be evaluated as *(p++)
So pointer p moves to next memory location.
say p was pointing to memory location 1012. p++ will make the pointer shift by data type size.
Here data type is int having size 2.
So you are getting weird and different results all time.
Use int pp=(*p)++;
EDIT:
You can confirm what I told by using arrays.
array reserves a continuous memory so if pointer moves to next array address you before hand know what is the output.
0
Hi, i played a little with your question... but I still can't explain what's happening to the value p is pointing to, when pp1 = *p++ is evaluated. analyzing the output it's obvious, that the initial value that p is pointing to is stored into pp1. but what happens then to the value in *p?
int *p = new int; // request memory
*p = 5; // store value
cout<< "initial value stored in p: ";
cout << *p << endl; // use value
int pp1 = *p++;
cout<< "pp1 = *p++: " << endl;
cout<< "value stored in pp1: ";
cout << pp1 << endl; // show value
cout<< "value stored in p now: ";
cout << *p << endl; // use value
int pp2 = (*p)++;
cout<< "pp1 = (*p)++: " << endl;
cout<< "value stored in pp2 = (*p)++: ";
cout << pp2 << endl; // show value
cout<< "value stored in p now: ";
cout << *p << endl; // use value
0
Check my profile for code. I have explored what the problem was. Megatron is absolutely right.👍