Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'new int (*)[10]' wrong? [duplicate]

I tried this code:

auto p = new int (*)[10];

but I got error messeage:

test.cc:8:21: error: expected expression
        auto p = new int (*)[10];
                           ^
1 error generated.

I changed my code:

typedef int array[10];
auto p = new array *;

And then everything goes well. Why is this?

like image 331
Hebbe FF Avatar asked Mar 11 '26 17:03

Hebbe FF


1 Answers

For details I refer you to https://en.cppreference.com/w/cpp/language/new.

Syntax for new without initializer is either

new (type)

or

new type

In the second case type may not contain parenthesis. This is also demonstrated in the above linked page:

new int(*[10])();    // error: parsed as (new int) (*[10]) ()
new (int (*[10])()); // okay: allocates an array of 10 pointers to functions

For your case that means:

auto p = new int (*)[10];     // error: parsed as (new int) ((*)[10])
auto p = new ( int (*)[10] ); // ok

When you use the alias, you can write

auto p = new array *;

because here type does not contain parenthesis.

like image 60
463035818_is_not_a_number Avatar answered Mar 14 '26 06:03

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!