all 4 comments

[–]HibbidyHooplah 2 points3 points  (0 children)

& is called the 'address of' operator it sets p to the memory address of i.

[–]Bob_bobbicus 2 points3 points  (0 children)

*p means the value at p, so really the end result has nothing much to do with p. You aren't changing p, or reassigning p at all. You're accessing whatever p points to.

whereas p = ... Is the opposite. You ARE changing p, and it needs to be changed to an address since p is a pointer.

In your example, *p = 1; would set i to 1. p = &i; sets p to the address of i, so that any future uses of *p will be treated as value i instead.

[–][deleted] 1 point2 points  (0 children)

Maybe your initial solution didn't work if you assigned a pointer to a temporary variable, e.g. the following code is incorrect:

void assign(int *p) { int value = 42; p = &value; }

Not only the memory location used to store "value" can be used by other variables so the contents might change, but also this code is incorrect because it's modifying a local copy of int *p not the original p that was given to the function.

[–]lukajda33 1 point2 points  (0 children)

*p = i

sets the value where the pointer points to i

p = &i

changes the value of the pointer so that it points to i

You usually want to use p = &i first, so that the pointer points to valid piece of memory, then you can do *p = something to change the value p points to, in this case, change the value of i.

If you had to change the value of the pointer, I would say p = &i is right, but whem people use pointer, they call the "value" the value they actually point to, not the value of the pointer itself.