how it is useful to use pointer to pointer in c++

I am trying to understand why would anyone use pointer to pointer i.e **p would anyone could give me an explanation? why would anyone use it in real life?
While using a pointer to a pointer can very useful, especially in C, it is usually better to try to avoid pointers whenever possible. In C++ prefer references and STL containers whenever possible.

Since C and C++ pass by value if you want to change where the pointer points inside a function you need to either pass the pointer by reference or pass a pointer to a pointer.

You don't generally see that form of "muti-star programming" in C++, that's more of a C thing. You're more likely to run into something like *PointerToObject->PointerInsideObject. Which makes a little more sense since you're passing the pointer to an object that itself contains a member that is a pointer. This could be because both of the object are large, or are being modified by the function it is being passed to so passing it by copy is useless. It could be that both the object and it's member are abstract classes. Those two reasons are off the top of my head, but there are plenty more.

You'll see pointers to pointers in API's that use functions which pass array's up to a higher ring. This is because sometimes you need complex data, but you don't want every joker writing directly into your protected memory space.
Last edited on
** is sometimes used as a 2-d array even though vector has largely replaces this usage. you can access it with x[rows][cols] type interface. You see this as well as an 'array of strings' when using c-strings, eg char **

Very old code that predates vectors, or was written back when vectors were new and had performance troubles in early libraries will use a lot of pointers, and a lot of that code is still out there, so at least being able to read it is useful. I wouldn't put such a thing in new code if at all avoidable.
Last edited on
Topic archived. No new replies allowed.