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*pis a place in the stack of typeintthat contains the address ofx(which we know is 25).So by saying
*pare we 'referencing' the address ofpwhich 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 = 5Simple enough, we're making a new place in the stack with the size of an
intpointer (whatever that may be).pwill 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
ppointing to? I mean, this does indeed work, but I never made aint x = 5or anything like that, and gave the address topto point to? How does it even know?pcontains 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
Ais a class first of all. Someone was saying theobject1stores the value ofA. Isn't that incorrect? Doesn'tobject1store the address of whatnew A()created and is pointing to it?Because
delete object1deletes the pointer, which points to thenew A()(but from the other questiondelete object1would 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 object1does indeed delete what the pointer is pointing to and not the pointer itself, doesn't this just leave a dangling pointer?