It is essential to understand that a pointer is a variable that holds a memory address.
This. This is probably the most important thing to understand about a pointer. It holds a number, and that number is an address in memory. When we say that a pointer "points to" some data, we mean that it contains the memory address where that data is stored.
Uses for pointers include:
- Getting around the pass-by-value problem (although in C++, we have references, which also solve this problem)
- Dynamic memory allocation
- Allowing the use of incomplete types, allowing us to remove unnecessary header file dependencies
- Array manipulation, as the name of an array is a pointer to the first element of the array (although in C++, you should be using STL container classes instead of C-style arrays, so it's best not to get into the habit of using them in the first place)
Pointers are a tough subject for people new to C++.
I often have days where i just can't seem to make them work right and others where we're good friends. (I'm a hard core noob myself though so take what i say with a grain of salt)
What made the idea click for me was the realization that a C++ program can only do ONE THING at a time. C++ is an OOP language yes, but it still only does one thing at a time. When its inside a function doing stuff, the only thing the program knows about is what it's currently doing (the stack, the code you wrote that's executing). If you want to access something somewhere else, you need a pointer to get to it as it's in memory (the heap).
Thinking about memory as kind of like a database where you can put stuff and pull it back again seems to sit best in my head.
Trying to use pointer variable without dereferencing them is a common source of error - mainly because someone forgot it was a pointer variable.
In C++, IMO, one should only use pointers if you need to, there are other safer alternatives.
We have references which are much better because they have to refer to a variable, unlike pointers which can be made to point to anything or nullptr - which is another source of error. One can get into strife with references, by returning a local reference from a function - which promptly goes out of scope as soon as the function ends. But on the whole they are a much safer alternative.
There is the already mentioned smart pointers.
And other things like the use of the auto keyword to help process all the elements in a container.