Bill Cunningham said:
"py is assigned the address of y", or equivalently, "py points to y." Y
hasn't been changed, nor has x; only py has changed to now point to y.
"y is assigned x." Nothing magical or pointery here.
In general, to get a pointer to a variable, use the address-of operator
on the variable. To do the reverse (to get a variable from a pointer to
that variable), use dereference.
1| int *p; // p is a pointer to an int
2| int x; // x is an int
3| int y; // y is an int
4|
5| p = &x; // &x is a pointer to an int (namely a pointer to x)
6|
7| y = *p; // *p is an int (namely x)
(Don't get the "*" on line 1 (the declaration of p) confused with the one
on line 7 (dereferencing p)--they have different meanings based on
context.)
If you'd like to change "y" at this point, you have two options. One is
to assign directly to it, like you did with "y=x". The other is to go
through "py", since you've set py up to point to y. This is where the
dereference would come in:
{
int x, y, *py; // not a dereference, just a declaration
y = 1; // normal assignment
printf("%d\n", y); // "1"
py = &y; // py points to y
printf("%d\n", *py); // dereference py to see the value of y: "1"
y = 2; // normal assignment
printf("%d\n", *py); // dereference py to see the value of y: "2"
printf("%d\n", y); // print y directly: "2"
*py = 3; // assignment into whatever py points at, namely y
printf("%d\n", y); // print y directly: "3"
x = 3490;
py = &x; // py now points to x
*py = 6502; // assign 6502 into whatever py points at, namely x
printf("%d\n", y); // y is still "3" from before
printf("%d\n", *py); // py points to x, so "6502"
printf("%d\n", x); // print x directly, "6502"
}
-Beej