Is there any difference between these two declarations?
int x[10];
vs.
int* x = new int[10];
I suppose th
According to the standard, we should actually distinguish between three different types of array declarations:
int x[10];
void method() {
int y[10];
int *z = new int[10];
delete z;
}
The first declaration, int x[10]
, uses static storage duration, defined by cppreference as: "The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern."
The second one, int y[10]
, uses automatic storage duration, defined by cppreference as: "The object is allocated at the beginning of the enclosing code block and deallocated at the end. All local objects have this storage duration, except those declared static, extern or thread_local."
The third one, int *z = new int[10]
, is usually referred to as dynamic memory allocation, and is actually a two-step sequence:
As already mentioned by other comments, these types of declaration have their subtle differences, but the most common ones are:
On most modern operating systems:
Dynamically allocated memory should be explicitly delete
-ed by the programmer, whereas static and automatic storage variables are taken care of by the "environment"
Static and automatic storage variables are limited to a specific scope, whereas dynamically allocated memory has no bounds, meaning, a variable declared in one module, can be passed to any other module that operates in the same address space
When allocating an array using new[]
, the size can be 0
(As already pointed out by @R Sahu) The types of &x
and &z
are different:
&x
is int (*)[10]
&z
is int **
If you want to size an array dynamically, e.g.:
void doSomething(int size)
{
int x[size]; // does not compile
int *z = new int[size];
//Do something interesting ...
doMore(z, size);
}
then x will not compile in C++, so you have to use z. The good news is that you can now use z, in most cases, as though it were statically allocated, e.g.:
void doMore(int anArray[], int size)
{
// ...
}
takes z as an argument, treating the pointer as an array.