Hey all, teaching myself CPP through a few books (and a little bit of CS in general through CS50) and hit a road block.
I understand what pointers are, and understand they’re a big part of programming. My question is why?
What do you use pointers for? Why is forwarding to a new memory address preferable to just changing the variable/replacing what’s already at the memory address or at a new one? Is it because new data could exceed the size of that address already allocated?
Thanks in advance!
To start off, as far as mental models go, you should look at pointers not as “forwarding to a new memory address” but as handles to an object. When you pass a pointer, you’re passing the address of where an object of a certain type already exists. You don’t create the object, you don’t copy the object. You just access where it already exists.
There are two different things in play: the pointer, and the object it points to.
The pointer only holds a memory address. As the name implies, a pointer points to a memory address. Dereferencing the pointer means accessing the object which is pointed to by the pointer.
The pointer only holds enough memory to represent a memory address, which nowadays is typically either 4 or 8 bytes. However, the object it points to can be and often is far bigger. Instead of being forced to copy that object, it’s often preferable to just pass a reference to it.