Pointing a pointer to another pointer - what happens?
Wonder if anyone can clear up the following for me. What happens if I point a pointer to another pointer ? E.g
Pointer 1 = Object
Pointer 2 = Pointer 1
What if I then change pointer 1 :
Pointer 1 = Ob开发者_开发问答ject 2
Where does pointer 2 now point ?
Thanks,
Martin
Pointer 1 = Object
Pointer 1 contains the address of Object.
Pointer 2 = Pointer 1
You assign the value of Pointer 1 to Pointer 2. The value of Pointer 1 is the address of Object. So Pointer 2 also contains the address of Object.
Pointer 1 = Object 2
Pointer 1 changes, but Pointer 2's value don't change. So Pointer 2 still contain the address of Object.
The things is a pointer contains the address, i.e. the value of a pointer variable is an address of memory. If you assign this to another pointer, then this address is assigned just like normal integer. However, pointing to a pointer (that is a pointer to pointer or **) is different from assigning a pointer to another.
You can google "C pointer tutorial" (well, Obj-C is superset of C and the pointer came from C part. Nothing special in Obj-C) for a better understanding. I would recommend this book specially for beginners.
Basically, say out loud what your code is doing. Pointer one points at an address of object 1. Pointer 2 points at the address of pointer 1. Changing the value of pointer 1 does not change the address of pointer 1. Not even when you free the content of pointer one.
It might help if you think of objects as closed boxes and pointers as baskets. You put a box in basket 1 and then put basket 1 in basket 2. If you thus remove the box from basket 1 and replace it with another box, does basket 2 suddenly contain something else?
精彩评论