12

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?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Hebbe FF
  • 131
  • 3
  • 3
    perchance, did you try `auto p = new (int (*)[10]);` ? – WhozCraig Mar 07 '22 at 12:28
  • 3
    See https://en.cppreference.com/w/cpp/language/new – HolyBlackCat Mar 07 '22 at 12:29
  • If that was really the only error message you got it kinda sucks, because it doesn't do much to identify the issue for you. What toolchain was that from anyway? – WhozCraig Mar 07 '22 at 12:31
  • 2
    @WhozCraig Both GCC and Clang give similar such error messages. MSVC is even worse and just says `syntax error: ')'`. But the error is exactly correct (but maybe not easy to understand), there should be an expression after the unary `*` operator. – user17732522 Mar 07 '22 at 12:34
  • @user17732522 interesting. my clang (apple 1300) reports: "this operator is not allowed at this point; parenthesize the preceding new expression" . must have gotten ahold of some special sauce. – WhozCraig Mar 07 '22 at 12:43
  • @WhozCraig That's what nvcc says: https://godbolt.org/z/Yo1jbjoPM and ICC similarly: https://godbolt.org/z/bbqcfanYs – user17732522 Mar 07 '22 at 12:50
  • 2
    In modern C++ explicit use of `new` is a bad practice. In this case you should use `std::vector` or `std::array`. – Marek R Mar 07 '22 at 12:58
  • new has its uses, particularly in polymorphism so I wouldn't call it bad practice. in this case those container classes would indeed be more appropriate and clearer. – Abel Mar 07 '22 at 13:31

1 Answers1

15

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185