I am curious if we have pointers and pointers to pointers to pointers, which variable must be deleted?
Anything that was created using new must be deleted. That's it.
Why couldn't we just delete the main pointer variables (in the two cases p and b) instead of *b?
Because then you would have things that were created using new that were never deleted. If you lost the pointer to them, you'd have a memory leak. The object that was created using new would never be destroyed. The memory would never be available for reuse.
If you're asking "if I delete a pointer to a pointer, why doesn't delete go down that chain and also delete the pointer it's pointing to?", the compiler isn't magic. It doesn't know when the right time to delete something is. What if you were still using something that was deleted? That would be a disaster.
if we want a stack pointer to point to a heap pointer, do we also use & to define the stack pointer?
Not to define it, no. Just to get its address.
1 2 3 4
int* pointer_on_stack; // this pointer is on the stack
int** pointer_on_the_heap = newint**; // this pointer is on the heap
pointer_on_the_heap = &pointer_on_stack; // now the object we made on the heap is pointing at the object we made on the stack
I am wondering why the code below doesn't work. The error states, " assigning to 'int ***' from incompatible type 'int **' p = &v;"
v is an object of type int*. So &v is an object of type int**.
p is an object of type int**, so *p is an object of type int*.
*p = &v
On the left: an int*
On the right: an int**
See the problem? Just because two items are pointers doesn't mean they're the same type. They're not. If you want to assign a value to a pointer, it has to be the same type.
Yea I see the problem but I figured it must be this way since the heap pointer *p points to the stack object v but v is also a pointer. Hm...maybe with two && instead of one? But that wouldn't make much sense.