I’m currently learning about pointers in my C++ Algorithms class and while I understand the material, I don’t understand why C++ makes pointers point to a memory slot and not to just a certain value that you could change later.
It would seem like you would want to be able to dynamically create a new variable in the very memory slot your pointer is taking up.
Is it because the Operating System creates all dynamic variables on the Heap and we need a way to find them because our pointer is made when the program loads?
If that is it then I totally understand that, but if that’s not it then it seems like a complete waste of memory space and an extra process our programs have to go through to access the destination value of the pointer.
Memory is actually saved in the case where you have large objects (by large I mean greater than 4 or 8 bytes, i.e.
sizeof(void *)). Instead of paying for expensive copy and overwrite operations you just pass a pointer – which is smaller than the object – and assign it that way.Dynamic allocation is for allocation that you can’t predict ahead of time, like variable-sized arrays and different state objects that you may or may not need depending on the conditions. You really don’t waste memory at all. If you passed them by value you would waste more time and more memory.
The pointer itself is a memory address but what it points to is a value in memory. This also applies to something like
int **because it points to a pointer value in memory.The operating system doesn’t create them dynamically, you do. You tell the program to allocate a new object or a certain sized memory block and the OS just gives it to you.
You can always reuse pointers. For instance, if I allocate space for a 100-byte array I can always reuse that as long as I keep a pointer to it, so long as I don’t free it until I’m done with that space (you’re actually encouraged to do so).