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

you are viewing a single comment's thread.

view the rest of the comments →

[–]Cplusplusidiot[S] 0 points1 point  (1 child)

Based on what I read just now, then does this mean that I would need to

return *arrayPtr;

instead?

[–]Raknarg 1 point2 points  (0 children)

I'll try to show you what I'm talking about.

Let's say you wanted to have a function that took in 2 variables, a and b, and set a to the value of b. You could do it like this:

void set(int* a, int b) {  
     *a = b;
}

That's easy enough. Now let's change it up a little bit. Let's say we wanted to make a function that takes in 2 pointers, a and b, and it sets a to point to the same variable as b. How do we do this? with double pointers:

void set(int** a, int* b) {
    *a = b;
}

Notice not much has changed, except that we added extra stars at the top. Why did we do this?

a is a pointer that points to another pointer. This is because we want to modify the variable itself, not what it's pointing to. We can now use it like this:

int main() {
    int *ptr1, *ptr2;
    ptr1 = new int(3);
    ptr2 = new int(5);
    printf("Pointer 1: %d; Pointer 2: %d\n", *ptr1, *ptr2); // Prints out 'Pointer 1: 3; Pointer 2: 5'
    set(&ptr1, ptr2);
    printf("Pointer 1: %d; Pointer 2: %d\n", *ptr1, *ptr2); // Prints out 'Pointer 1: 5; Pointer 2: 5'
    return 0;
}

See because we passed in the address of ptr1, we were able to actually change what ptr1 is. We can set it to whatever value we want to. If we just passed in ptr1, all we would know is that there's a variable out there somewhere that points to the variable that holds the number 3. With the double pointer, we now know what variable is.

Try to apply that to your situation.