Search code examples
c++arraysnew-operator

C++: array types and new


I'm learning C++. The following program looks nice and generic:

typedef some_type T;
int main() {
  T* p = new T;
}

And it indeed works for non-array types like int, etc. However, if I try typedef int T[2]; it breaks with the error :

cannot convert 'int*' to 'int (*)[2]'.

What's the logic here? Is there anything I could do to new to make it return an object of the correct (for this pointer) type?

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

FWIW, new int[2] doesn't work either. Maybe I'm missing some syntax here, the general idea would be to allocate an object of type T where type T happens to be an array of two ints.


Solution

  • Maybe I'm missing some syntax here

    First note that T* is actually int(*)[2].

    Now, there are two options/answers here:

    One valid syntax is:

    T* p = new int[2][2];
    

    Or another equivalent valid syntax is:

    T* p = new T[2]; //this is also valid in c++
    

    Btw you should use std::array and smart pointers in modern c++.