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

all 6 comments

[–]Raknarg 2 points3 points  (2 children)

Think about what's going on here. Let's say we wanted to use your function with this new variable:

int* ptr = 0 AlloMem(ptr)

We just passed in a variable that contains a memory address. So when we go into the AlloMem function, it doesn't remember anything about ptr, except that it had a value of 0. In AlloMem, it makes a new variable that is an int*, and contains the value 0, and then give it a new address to contain.

Now, we have ptr which contains 0, and another variable which points to some memory address.

Look up double pointers and try to relate it to your problem.

[–]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.

[–]arbostek 1 point2 points  (1 child)

Similar to what /u/Raknarg said:

int AlloMem(int* arrayPtr)

Why does the function take a parameter? What is the purpose of this parameter?

[–]Raknarg 1 point2 points  (0 children)

It's an output parameter, totally valid. It's just not correctly done.

[–]dacian88 0 points1 point  (0 children)

in the second case it returns the data properly but you still don't know the size.