Reputation:
I am having issues understanding pointers in C++. I thought I understood, but after this practice, it seems to be a challenge.
int main() {
int x, y, z;
int *p =&x, *q = &y, *r =&z;
*p = 7;
*q=4;
*r = (x+y) * 4;
*p=*q;
x = (*q) + (*r);
p=q;
q=r;
*r=*p;
y = (*r * 3) +y;
cout<<x << " " << y << " " << z<<endl;
cout<< *p<<" " << *q << " " << *r<< endl;
return 0;
}
My thought process: p and x = 7, q and y = 4. and r and z = 44. Then p = q so x = 4. Then we change x to 48. Now when p=q and q=r, I am not sure what happens. Can anyone assist me to understand? Thank you
Upvotes: 0
Views: 74
Reputation: 36082
+-----+
p -> | x |
+-----+
+-----+
q -> | y |
+-----+
+-----+
r -> | z |
+-----+
p = q
+-----+
| x |
p +-----+
\
\ +-----+
->| |
->| y |
/ | |
/ +-----+
q
+-----+
r -> | z |
+-----+
q = r
+-----+
p | x |
\ +-----+
\ +-----+
->| |
| y |
+-----+
q
\
\ +-----+
->| |
->| z |
/ | |
/ +-----+
r
Upvotes: 2
Reputation: 11256
p=q
assigns to p
pointer the value of q
pointer which is the address of y
, so after this assignment p
actually points to y
.
The other part is similar.
Upvotes: 3