What would be the point of a double pointer? ( No pun intended :] )

This topic is 3673 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I understand how pointers work, but what would be the purpose of a double pointer? I've seen only a few, but when I do see them, I don't understand why/how they have a purpose for being helpful. Could someone explain this better for me? example in case people don't know what I'm asking:
int** two_of_them;
SomeClass** twoOfThem;



Share on other sites
Lots of uses really, though a reference to pointer can often be used instead.

If you want to pass a pointer into a function and have said function modify where
the pointer points then you would likely want to pass it as ** or *&.

Or if you have a pointer to an array of pointers you might use it also.

Share on other sites
The above information is good. Some examples:

int *ptr = 0;void MakeAPtr(int *&ptr) { ptr = new int[2]; }void MakeAPtrDoubleStar(int **ptr) { *ptr = new int[2]; }//cleanupdelete [] ptr;int **ptrArray = 0;ptrArray = new int* [2];for(int i = 0; i < 2; ++i) ptrArray = new int[8];ptrArray[1][7] = 3;//cleanupfor (int i = 0; i < 2; ++i) delete [] ptrArray;delete [] ptrArray;

I should mention, that even though this looks like a handy way to do a two dimensional array, you probably shouldn't. There's a ton of memory allocations and they could be all over memory.

Only do it this way if you need 1.) a dynamic number of arrays, and 2.) the arrays are staggered in length.

Another example:
int **MakeArrays(int cnt, int lengths[]){  int **output = 0;  output = new int* [cnt];  for (int i = 0; i < cnt; ++i)    output = new int[lengths];  return output;}int arrayCnt = 3;int arrayLens[3] = {2,5,4};int **data = MakeArrays(arrayCnt, arrayLens);

If you dont need a dynamic number of arrys, do it with a fixed ptr array.

int *arrays[3];

If you dont need them to be staggered in length, use one big array.

int arrayCnt = 3, arrayLen = 5;
int *data = new int[arrayCnt * arrayLen];

Share on other sites
Oh it does come in handy. :]
I didn't realize that *& and ** passed like that were the same ( in a way, mind you ). I've been using those all along and didn't realize it. :] Thanks for the clear-up.

Share on other sites
Yep. The only difference is obviously that the reference part is constant, whereas a double pointer can be reassigned and requires explicit address-of (&obj) and dereference (*p) operators.

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 16
• 12
• 20
• 12
• 14
• Forum Statistics

• Total Topics
632155
• Total Posts
3004477

×