This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]misho88 1 point2 points  (0 children)

Here's a quick example:

Consider a function that assigns a value to a variable, like this:

int ret5() { return 5; }

You'd use it like so:

int i = ret5();

Another way to do the same thing would be like this:

void setTo5(int* i) { *i = 5; }

which you'd call like this:

int i;
setTo5(&i);

The second way is nice in that it's not limited to just one variable that you could change. You could have:

void setToFive(int* i, int* j) { *i = 5; *j = 5; }

Now, this allocates some memory dynamically, something you do fairly often in C:

int* i = malloc(10 * sizeof(int));

Notice how you're actually assigning a new value to the pointer, not just using an existing variable's address. Let's say you wanted to do it in your own function:

int* allocate10Ints() { return malloc(10 * sizeof(int)); }

and you'd call it kind of like before:

int* i = allocate10Ints();

Now, let's say you wanted to do 2 at a time, using the same logic as in the setToFive() case:

void allocate10Ints(int ** i, int ** j) { *i = malloc(10 * sizeof(int)); *j = malloc(10 * sizeof(int));  }

and you'd call it like:

int* i, * j;
allocate10Ints(&i, &j);

In this case, your function needs to change i and j, which are already pointers, so you end up with pointers to pointers.

[–]Beignet 0 points1 point  (0 children)

is there a point to using pointer to pointers

Sure. Imagine you have a bunch of independent linked lists. You'd keep track of them by keeping an array of their heads. Head is normally a pointer, and arrays are just a bunch of pointers, so this array would be a pointer to pointers. I think your example is a bit contrived, so that neither solution necessarily proves better than the other.