Search code examples
c++dynamic-memory-allocationnew-operator

What is the difference between given two lines of dynamic memory allocation in C++ ? Do they both create 10 sized array?


int *arr = new int(10);

int *arr = new int[10];

It is the code of dynamic memory allocation in c++. But I am not getting What is the difference between these two.


Solution

  • For a simple example, let's talk about what happens on the stack.

    int x(10)
    This generally means assigning an value to an int named x.

    int x[10]
    This generally means creating an array named x of 10 elements.

    So, when it come to dynamic memory, it's the same thing.

    int* x=new int(10)
    This creates a single integer on the heap and assigns it the value 10.

    int* x=new int[10]
    This creates an array of 10 integers on the heap.