Search code examples
c++arraysdynamicheap-memoryallocation

Dynamic Arrays in C++ (Array of pointers or new array?)


If I want to create an dynamic array of objects:

I can create an array using the new keyword where C++ will automatically create an array of node objects and call the default constructor for all nodes.

node* nodes = new node[10];

Or I can create an array of pointers to nodes and instantiate the nodes individually.

node* nodes[10];

for (int i = 0; i < 10; i++)
{
    nodes[i] = new node();
}

When would it be appropriate to use either? In the first example, are the nodes still dynamically allocated when using the new keyword with an array?

Many thanks!


Solution

  • Between these two code snippets there is a big difference.

    In the second case that is when the following definition is used

    node* nodes[10];
    

    you can not add new elements to the array. The array has fixed size.

    In the first case when you use operator new for the whole array

    node* nodes = new node[10];
    

    the array can be reallocated with an arbitrary number of elements.

    So the main criteria is whether you need an array of fixed size or not, whether the underlying class has a default constructor or not.