Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not initialize an array by passing a pointer to a function?

Tags:

c++

pointers

I know this has a really simple explanation, but I've been spoiled by not having to use pointers for a while.

Why can't I do something like this in c++

int* b;
foo(b);

and initialize the array through...

void Something::foo(int* a)
{
  a = new int[4];
}

after calling foo(b), b is still null. why is this?

like image 235
Erix Avatar asked Nov 28 '22 19:11

Erix


1 Answers

Pointers are passed to the function by value. Essentially, this means that the pointer value (but not the pointee!) is copied. What you modify is only the copy of the original pointer.

There are two solutions, both using an additional layer of indirection:

  1. Either you use a reference:

    void f(int*& a) {
        a = new int[4];
    }
    
  2. Or you pass in a pointer-to-pointer (less conventional for out parameters as in your case):

    void f(int** pa) {
       *pa = new int[4];
    }
    

    And call the function like this:

    f(&a);
    

Personally, I dislike both styles: parameters are for function input, output should be handled by the return value. So far, I've yet to see a compelling reason to deviate from this rule in C++. So, my advise is: use the following code instead.

int* create_array() {
    return new int[4];
}
like image 85
Konrad Rudolph Avatar answered Mar 14 '23 00:03

Konrad Rudolph