new
is for dynamic allocation (of an array on the heap in this case), and returns a pointer to the new array.
[]
in the declaration are for declaring it to be a stack array (and the brackets belong the right side of the variable name).
So the two legal approaches your code is mixing would simplify to either:
int a[10]; // Declares a stack array of size 10
or:
int *a = new int[10]; // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`
The former is the better solution here (there’s no benefit to a heap allocation for such a small array that is only used within the scope of this function, and it would require explicit delete[] a;
later to properly clean it up).
That said, neither version initializes the values, so the contents of a[0]
are uninitialized, and reading from them will get random garbage. Both versions can be changed to initialize the data with zeroes though, e.g.:
int a[10] = {0}; // Declares a stack array of size 10 and initializes to zero
or:
int *a = new int[10](); // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`, initializing to zero
Final note: Using raw new
is generally frowned upon in modern C++. If you needed heap-allocated contiguous data storage, you’re probably better off using a std::vector
.
0
solved C++ What’s the problem in this line? int [] a = new int[size]; [closed]