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

Started by
3 comments, last by thre3dee 15 years, 9 months ago
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;
/*See what I'm asking now?*/

Thanks in advanced! ~Maverick
Holy crap, you can read!
Advertisement
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.
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];
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.
Holy crap, you can read!
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.

This topic is closed to new replies.

Advertisement