Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dereference a pointer -vs- &-operator

Would these two assignments be equivalent, i.e. perfom exactly the same thing?

*pointer = object

pointer = &object

, where pointer is a pointer to an "object-instance".

Or does this only make sense for primitive types.

like image 698
Patrik Meijer Avatar asked Aug 30 '26 21:08

Patrik Meijer


2 Answers

No, these are not the same.

pointer = &object sets pointer so that it points at object.

*pointer = object sets the value of thing being pointed to by pointer to be equal to the value of object.

like image 94
Oliver Charlesworth Avatar answered Sep 02 '26 11:09

Oliver Charlesworth


Absolutely not.

*pointer = object

changes the memory the pointer points to.

pointer = &object

changes the pointer.

pointer   ---->    object1
&object   ---->    object

In the first case, this becomes:

pointer   ---->    object
&object   ---->    object   

In the second case:

                  ---->    object1 //could turn into a memory leak
&object, pointer  ---->    object
like image 23
Luchian Grigore Avatar answered Sep 02 '26 12:09

Luchian Grigore