What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?
A pointer variable (or pointer in short) is basically the same as the other variables, which can store a piece of data. Unlike normal variable which stores a value (such as an int, a double, a char), a pointer stores a memory address. Pointers must be declared before they can be used, just like a normal variable.
Pointers are used to store and manage the addresses of dynamically allocated blocks of memory. Such blocks are used to store data objects or arrays of objects. Most structured and object-oriented languages provide an area of memory, called the heap or free store, from which objects are dynamically allocated.
One function passes a pointer to the value of an object to another function. Both functions can access the value of that object, but the value itself is not copied.
Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.
Pointers are best understood by C & C++'s differences in variable passing to functions.
Yes, you can pass either an entire variable or just a pointer to it (jargon is by value or reference, respectively).
But what if the variable is 20 meg array of bytes, like you decided to read an entire file in to one array? Passing it by value would be foolish: why would you copy 20 megs for this operation, and if you end up modifying it (i.e. it's an out-parameter) you have to copy that 20 megs BACK?
Better is to just "point" to it. You say, "here's a pointer to a big blob of memory". And that little indirection saves a ton of time.
Once you understand that, everything else is basically the same. Rearranging items in a list becomes just swapping pointers rather than copying every item around, you don't need to know how big things are when you start out, etc
Pointers are most useful when dealing with data structures whose size and shape are not known at compile-time (think lists, trees, graphs, arrays, strings, ...).
Edit
These related answers might also help (the top answer in the second link is definitely worth a look):
In C++ I Cannot Grasp Pointers and Classes
What are the barriers to understanding pointers and what can be done to overcome them?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With