2

When I edit the flowing code:

int (*p)[2] = new int [2][2];  //it's right.
int (*q)[2] = new int (*)[2];  //it's wrong.
//the wrong message:error: expected primary-expression before ')' token.
//compile by g++ in Code::Blocks,Debug.

I can understand the first one. But,why can't the second one work?

How does the compiler match the type? Obviously,it doesn't match like the general condition, and there must be some limits for new. I think I ignore some principles.

umläute
  • 28,885
  • 9
  • 68
  • 122
willaty
  • 23
  • 3
  • 8
    what do you think (*) is doing? or should be doing? – Hayt Sep 15 '16 at 08:09
  • 1
    If I want new a pointer to an array,must i new int [1][2]? //it's my other idea. – willaty Sep 15 '16 at 08:12
  • a pointer to an array is `new int[]` Doing [2][2] creates an array (of the size 2) of arrays (of the size 2) – Hayt Sep 15 '16 at 08:14
  • new int [] return the int*,I want the (*)[2]...Quentin give the answer, I should add the brackets and change the return type.Thank you for answer me!(But I don't know why should I add the brackets.) – willaty Sep 15 '16 at 08:30
  • Yes, `new int[1][2]` is the simplest way to do what you're trying to do – M.M Sep 15 '16 at 12:28

1 Answers1

4

I kind of steamrolled the problem here: the first thing I tried works, but I don't have the insight into why it works. You simply have to add parentheses:

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

Also note that newing a T returns a T*, so newing a pointer returns a pointer-to-pointer.

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • 5
    I think I have it: `new int(*)[2]` is parsed as `new []` where `T` is `int(*)` which doesn't make sense. Your version is `new` with `T = int (*)[2]` pointer to array of int. So you basically allocate 1 pointer to array. – bolov Sep 15 '16 at 08:20
  • I think, maybe the new will distinguish the array-type and non-array-type.I check: new int[2][2] and new (int[2][2]) are work.Adding the brackets is better.Maybe only after reading the implement of new can i know more details. – willaty Sep 15 '16 at 08:55
  • 1
    Things sure would be more readable with `using T = int(*)[2]; T* q = new T;` – MSalters Sep 15 '16 at 09:14