Search code examples
c++new-operatordynamic-memory-allocation

Dynamic allocation array difference in C++


Today I came across a new type of allocation in cpp which I never heard of any I tried to search google but didn't find any related answer.

long int *a=new long int[N+1]();

I know long int *a = new long int[N+1];

But what is the difference between the two above?


Solution

  • long int *a = new long int[N+1]();
                                   ^^
    

    Allocate memory, and initialize them to the default state of the type (for built-in types, zero). It's the standard way to initialize objects allocated by new so they do not contain indeterminate values (no UB, though). In C++11, you can also use curly brackets:

    long int *a = new long int[N+1]{};
                                   ^^