views:

45

answers:

3

Hi all,

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 = Object 2

Where does pointer 2 now point ?

Thanks,

Martin

A: 

Suppose we have a type struct Foo. I'm assuming you mean something along the lines of:

struct Foo obj1;
struct Foo *ptr1 = &obj1;
struct Foo *ptr2 = ptr1;

In this situation, we have two pointer variables containing the address of obj1. Nothing more, nothing less. If you change the value of ptr1,

ptr1 = &obj2;

then nothing happens to ptr2, so it still points at obj1. No magic link is introduced between ptr1 and ptr2 by assigning the same value to them at some point.

larsmans
+1  A: 
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.

taskinoor
A: 

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?

Workshop Alex