0

I am currently learning pointers in C++ and I learned that you could have pointers to pointers. However, I do not know how I would use it in a real world scenario and why it is so useful. Can someone help me with this?

I have tried looking this up but I have basically only found how to write codes that use pointers to pointers but not what type of situations call for pointers to pointers.

  • 1
    Among other things, imagine a case in which a function might have to modify a pointer parameter: `fun(list **head)` – jkb Jun 12 '23 at 00:22
  • 1
    `void AddNode(Node** head, Node* node);` can be used to add a node to a tree, and if that node itself becomes the head node, also update the head node pointer to point to the (new) head node. Although that's more of a C idiom, and in C++ it would probably be done `void AddNode(Node*& head, Node* node);`. – Eljay Jun 12 '23 at 00:23
  • 1
    *"I do not know [...] why it is so useful."* -- you made a jump in meaning here. You learned that pointers-to-pointers are *allowed*. That is not the same as "useful". The logical leap from "allowed" to "useful" can be justified if you first know how you would use it in a real-world scenario. Which you don't know yet... – JaMiT Jun 12 '23 at 00:40
  • While this question isn't bad, it's a sign you need a good [C++ reference](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to consult first. Pointers to pointers can be very useful when you need to manipulate a supplied pointer, as is common with linked list implementations. That being said, in C++ **try and avoid using pointers** and instead steer towards references and cheap-to-copy objects. Where pointers are unavoidable, there are pointer wrapper containers that help manage memory. – tadman Jun 12 '23 at 00:53
  • 1
    none of the `list **head` and `Node** head` examples above are useful in C++ because there are alternatives better in every way. Short answer: in C++ there aren't many useful scenarios for them. In C that's totally another situation but since you are talking about C++ you will seldom encounter them, except in legacy code. Now please note I am not saying that means it's not useful to be proficient with them. – bolov Jun 12 '23 at 01:13
  • Ever since C++11 was released I never needed pointers to pointers anymore , in practice it is just too easy to write buggy code with them. The only use cases I can think of are "interaction with legacy API's" , and maybe just maybe internally inside a specific datastructure class. In almost all other cases I tend to use (nested) containers. – Pepijn Kramer Jun 12 '23 at 06:12
  • There is nothing special about pointers; all they do is tell you where something is. Imagine a world where you want somebody's address but the phrase "please write it down on the paper over there" could never exist. – molbdnilo Jun 12 '23 at 07:45

0 Answers0