C++ Allocate dynamic array inside a function

kevin labille picture kevin labille · Nov 13, 2014 · Viewed 11k times · Source

so I need to allocate an array of int inside a function. The array is declared before calling the function (I need to use that array outside the function) and the size is determined inside the function. Is it possible ? I have been trying a lot of thing but nothing worked so far.

Thanks for your help guys ! Here is some code :

void fillArray(int *array)
{
  int size = ...//calculate size here
  allocate(array, size);
  //....
}

void alloc(int * &p, int size)
{
  p = new int[size];
}

int main()
{
  //do stuff here
  int *array = NULL;
  fillArray(array);
  // do stuff with the filled array
 }

Answer

Vlad from Moscow picture Vlad from Moscow · Nov 13, 2014

If I have understood correctly you did not declare an array before calling the function. It seems that you declared a pointer to int instead of an array. Otherwise if you indeed declared an array then you may not change its size and allocate memory in the function.

There are at least three approaches to do the task. The first one looks like

int *f()
{
    size_t n = 10;

    int *p = new int[n];

    return p;
}

And the functionn is called like

int *p = f();

The other approach is to declare a parameter of the function as having type of pointer to pointer to int. For example

void f( int **p )
{
    size_t n = 10;

    *p = new int[n];
}

and the function can be called like

int *p = nullptr;

f( &p );

The third approach is to use reference to pointer as the function parameter. For example

void f( int * &p )
{
    size_t n = 10;

    p = new int[n];
}

and the function is called like

int *p = nullptr;

f( p );

The better way is to use standard class std::vector<int> instead of a pointer. For example

void f( std::vector<int> &v )
{
   size_t n = 10;

   v.resize( n );
}

and the function can be called like

std::vector<int> v;

f( v );

Also you could use a smart pointer like std::unique_ptr