Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Array *new Array; fails in C++? [duplicate]

I always thought T *p = new T; was valid C++ for all T... until I tried

int main()
{
    typedef int Array[2];
    Array *p = new Array;
}

and got this cute error I couldn't decipher:

error C2440: 'initializing' : cannot convert from 'int *' to 'Array (*)'

Could someone please explain why this is an error?

like image 867
user541686 Avatar asked Jan 04 '14 09:01

user541686


People also ask

Can C double array?

You can declare an array of any data type (i.e. int, float, double, char) in C. The following ways can be used to declare and initialize an array in C.

Can an assignment operator copy one array to another in C?

Arrays are not assignable. You cannot use an array type variable as LHS operand of assignment operator. An assignment operator shall have a modifiable lvalue as its left operand.

Can assignment operator copy one array to another?

We can create a copy of an array by using the assignment operator (=).

Do C arrays need to be freed?

No they don't get freed automatically, but depending on how you allocated each of them, there might be no need to free them actually. You would only need to free them if they point to memory which was returned by malloc and similar allocation functions. Note in this case you don't need to free the array itself.


2 Answers

If you dynamically allocate an array type, you get a pointer to its first element.

§5.3.4 [expr.new] Entities created by a new-expression have dynamic storage duration. If the entity is a non- array object, [...]. If it is an array, the new-expression returns a pointer to the initial element of the array.

So since you're allocating an array type object, you get an int* out of it:

int *p = new Array;

This is no different to not using the typedef:

int *p = new int[2];

This also doesn't match your T *p = new T; rule. That is, you definitely can't do this:

int (*p)[2] = new int[2];

I realise this confusion may have been caused by thinking of new ...[] as a special type of expression different to new ..., where new Array fits into the latter case. We often suggest it might be by saying things like "new[] should always match with delete[]". Well that rule is a little misleading. What is really meant here is that new with an array type should always be matched with delete[].

like image 112
Joseph Mansfield Avatar answered Sep 29 '22 11:09

Joseph Mansfield


The problem here is that array type syntax in C and C++ is a jumbled mess, and typedefing an array type to something that doesn't look so jumbled doesn't make it any less so.

The result, in an expression, of dynamically allocating an array is a pointer, not an array. The types are different.

like image 28
Lightness Races in Orbit Avatar answered Sep 29 '22 12:09

Lightness Races in Orbit