A double pointer is nothing more than a pointer to another pointer. It’s possible to continue this pattern indefinitely having pointers to pointers to pointers, and so on. But you’ll rarely need more than a double pointer.
Previous episodes explained how you can use pointers to either point to a group of items or to individual items within a collection. Now you learn how to use a pointer that points to another pointer.
Let’s say we have two items: ItemA and ItemB and they both live somewhere in memory. It doesn’t matter where or in what order they are to each other.
Now you have a pointer to each of them called pItemA and pItemB and for these pointers, you do want them positioned in a certain order. If you want ItemA to come before ItemB, then put pItemA in front of pItemB. Pointers are small and can be moved around in memory very easy. Maybe a lot easier than trying to move the actual ItemA and ItemB themselves.
Now that you have your two pointers to the items positioned in memory one right next to the other, you can refer to them both with another pointer. We’ll create another pointer called pItemCollection and make it point to whichever of the item pointers is first. In this case, pItemCollection will point to pItemA.
So far, you should be able to understand this if you take it one step at a time. It will help if you draw it on paper. Use boxes for each of the items and for each of the pointers and use arrows from each pointer that goes to whatever it points to.
The difficult part comes when trying to understand how to call a method that can modify your pItemCollection pointer. You can’t pass the pointer directly to the method because then it will get its own pointer value that also points to pItemA. So what you need to do is provide the method with the address of where your pItemCollection pointer lives in memory so that it can change it directly. You pass the address of something with another pointer.
We’ll talk about this again when I explain methods.