Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What real use does a double pointer have?

Tags:

c++

pointers

I have searched and searched for an answer to this but can't find anything I actually "get".

I am very very new to c++ and can't get my head around the use of double, triple pointers etc.. What is the point of them?

Can anyone enlighten me

like image 469
Mark Green Avatar asked Feb 27 '18 18:02

Mark Green


People also ask

What are double pointers used for?

A pointer is used to store the address of variables. So, when we define a pointer to pointer, the first pointer is used to store the address of the second pointer. Thus it is known as double pointers.

What is the advantage of double pointer?

With double pointers You can reorganize tons of data in the memory by simply referring to the memory address A Pointer as the name implies points to a location in the memory. It holds the address of the variable it is pointing to. Single pointer directly points to address of the variable.

What is the actual use of pointer?

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.

What is pointers What is the use of having double triple and quadruple pointers?

Double and triple pointers are often used for 2 reasons – passing a pointer to a function and dynamic allocation of memory for 2D and 3D arrays. The use of pointers for dynamic memory allocation is described in C++ Dynamic Memory.


1 Answers

Honestly, in well-written C++ you should very rarely see a T** outside of library code. In fact, the more stars you have, the closer you are to winning an award of a certain nature.

That's not to say that a pointer-to-pointer is never called for; you may need to construct a pointer to a pointer for the same reason that you ever need to construct a pointer to any other type of object.

In particular, I might expect to see such a thing inside a data structure or algorithm implementation, when you're shuffling around dynamically allocated nodes, perhaps?

Generally, though, outside of this context, if you need to pass around a reference to a pointer, you'd do just that (i.e. T*&) rather than doubling up on pointers, and even that ought to be fairly rare.

On Stack Overflow you're going to see people doing ghastly things with pointers to arrays of dynamically allocated pointers to data, trying to implement the least efficient "2D vector" they can think of. Please don't be inspired by them.

In summary, your intuition is not without merit.

like image 91
Lightness Races in Orbit Avatar answered Sep 30 '22 18:09

Lightness Races in Orbit