I have a few silly questions (probably for most), it's less about 'how' do I do them and more about 'why' do they work this way? I know you are not supposed to ask multiple questions, but these are fairly small and related to one topic. Seems like it'd be a waste to separate them out.
I understand for the most part pointers, and the operators themselves. (Although I am curious why the
*
is called the de-reference operator, since isn't it referring to a reference of what it contains?)I.e:
int x = 25; int *p = &x;
So
&
makes sense, since*p
is a place in the stack of typeint
that contains the address ofx
(which we know is 25).So by saying
*p
are we 'referencing' the address ofp
which is pointing to the 25. Maybe it's just an English semantics thing? Maybe someone can explain why it's called 'de-reference'?Take this valid code sample:
int *p = new int; *p = 5
Simple enough, we're making a new place in the stack with the size of an
int
pointer (whatever that may be).p
will contain some address that has a 5 for a value.Thing is, I haven't actually declared anything that's storing a 5, so what the heck is
p
pointing to? I mean, this does indeed work, but I never made aint x = 5
or anything like that, and gave the address top
to point to? How does it even know?p
contains an address that points to something, but I never made that 'address' it's pointing to? Does the compiler just know to create another address somewhere else? (Sorry if this is a really stupid question.)I was reading on here about some memory leaks on another question:
A *object1 = new A();
pretending
A
is a class first of all. Someone was saying theobject1
stores the value ofA
. Isn't that incorrect? Doesn'tobject1
store the address of whatnew A()
created and is pointing to it?Because
delete object1
deletes the pointer, which points to thenew A()
(but from the other questiondelete object1
would indeed be the correct syntax. So does that leave thenew A()
hanging out there? Or does it get automatically deleted? (As you can tell I'm a bit confused.)If
delete object1
does indeed delete what the pointer is pointing to and not the pointer itself, doesn't this just leave a dangling pointer?