Sign in to follow this  
Maverick Programmer

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

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;
/*See what I'm asking now?*/

Thanks in advanced! ~Maverick

Share this post


Link to post
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 this post


Link to post
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]; }

//cleanup
delete [] ptr;


int **ptrArray = 0;
ptrArray = new int* [2];

for(int i = 0; i < 2; ++i)
ptrArray[i] = new int[8];

ptrArray[1][7] = 3;

//cleanup
for (int i = 0; i < 2; ++i)
delete [] ptrArray[i];

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[i] = new int[lengths[i]];

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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this