Don't understand this code.
| DwLee (3) | |||
Could someone explain this code in detail please? I felt that the tutorial briefly touched this subject. Anyways, I understand this much. P1 and P2 are equal to the address of the first and second values. The value pointed to be P1 is 10, so in turn the first value must equal 10. Then the value pointed to by P2 is equal to the value pointed by P1, I think. So this would make the second value 10 too, right? Then the tut says that by "p1 = p2", the value is copied, but isn't the address copied? How in the world does p1 end up pointing to the value of 20? | |||
| nogoodatall (9) | |||
| P1 and P2 are equal to the address of the first and second values. they are not equal to the value, but they point to the memory space that holds the values of firstvalue and secondvalue. The value pointed to be P1 is 10, so in turn the first value must equal 10. correct, because p1 points to firstvalue memory space, it changes the value of firstvalue to 10 Then the value pointed to by P2 is equal to the value pointed by P1, I think. So this would make the second value 10 too, right? correct, it basically says copy what is in the memory space p1 points to into the memory space p2 points to. because the value p1 points to is 10, now the value p2 points to is 10. Then the tut says that by "p1 = p2", the value is copied, but isn't the address copied? your are right, the address is copied not the value. So now p1 points to the memory space that p2 does(and the value of that space) How in the world does p1 end up pointing to the value of 20? *p1 = 20; is setting the value of the memory space that p1 points to, to the value of 20. Because p1 now points to p2's memory space, this in turn changes the value that p2 points to as well. Remember that a pointer does not hold any values. It just points to a memory space of the same data type. | |||
| DwLee (3) | |||
| If P1 now points to the address AND value of P2, then it would remain 10 wouldn't it? *p2 and *p1 = 10 If it would, I still don't see where 20 comes from. When did we ever add? | |||
| vince1027 (82) | |||
It's already answered for you...
| |||
| DwLee (3) | |||
| Oh! So there is no addition or anything, we just changed the value of what P1 is pointing to, which in turn changes the value of P2 because of P1 = P2. If this is correct, then I was making it was more difficult than it really was. | |||
This topic is archived - New replies not allowed.
