Why is
int *a = new int[10];
written as
int *a;
a = new int[10];
instead of
int *a;
*a = new int[10];
?
The way I see it, in the second block of code you’re saying a, which was a pointer variable, is now an array. In the third block of code you’re saying the thing a points to is now an array. Why does the second make more sense than the third?
new int[10]returns a pointer to the first element in the array (which is of typeint*). It does not return a pointer to the array (which would be of typeint(*)[10]).a = new int[10]means makeapoint to the first element of the dynamically allocated array.*ais not a pointer at all. It is the object pointed to by the pointera(which is of typeint).Note that if you actually had a named array object, the syntax would still be the same:
Why? In C++, in most cases, whenever you use an array, it is implicitly converted to a pointer to its initial element. So here,
int* a = xis the same asint* a = &x[0];.(There are several cases where the array-to-pointer decay does not occur, most notably when the array is the operand of the
&orsizeofoperators; they allow you to get the address of the array and the size of the array, respectively.)