Hello guys, i'm trying to undestand "pointers" and i'm struggling a bit. Could you please explain me the basics of this prototype, what can i do with a pointer, how do i integrate them into a basic problem(at first)? Thank you.
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (1)
Short answer: variable holds the value and pointer holds the memory address.
When you declare 2 variables with the same value, they live in different memory space, rough example:
When you declare 2 pointers with the same value, they refer to the same memory space:
similarly, another
ptY
also refering to the memory space thatvarA
lives in.When you change
varA
, bothptX
andptY
are aware of the updated value since they refer to wherevarA
lives:So why is this useful? How could this meta programming be utilised? 2 scenarios on top of my head:
A. Function that updates its argument:
This is not always a good idea, but in C, when you call a function, the arguments you pass to it are copied in order to execute the code inside:
What happens here is that
var
is copied, somyVar
within the function is not the same as thevar
you declare, thus modifyingmyVar
has no effect onvar
. On the other hand:This is called passing by reference, where you don't want the function to copy you arguments but rather refer to the same variables.
B. Dereferencing objects.
When you declare a class and create multiple objects from that class, in many cases it doesn't make much sense to "compare" 2 objects with
==
.More specifically, what are we comparing? Is it the value of each property that both objects hold? What about object that holds other objects as its property, how deep are we descending? What about object that has lambda function as its property, which get created by its caller? How do you "compare" 2 functions?
So in many cases you deal with object reference, or object pointer (referring to the memory space that your object lives in), and you ask the question "are these 2 pointing to the same object?".
And since objects usually represent something meaningful, e. g. User object represents an actual user, you want to have several methods referring to/ updating 1 User object living in memory (using a User pointer), instead of creating multiple User objects and let their values go out-of-sync with each other.