koponomarenko koponomarenko - 1 month ago 13
C++ Question

c++ creating a static like array with "new" or another way of creating a dynamic array

I know that the common technique of creating a dynamic array in C++ is:

int * arr = new int[5];


A book also says:

short tell[10]; // tell an array of 20 bytes
cout << tell << endl; // displays &tell[0]
cout << &tell << endl; // displays address of the whole array
short (*p)[10] = &tell; // p points to an array of 20 shorts


Now I wonder if there is a way to allocate memory for an array using "new" so it can be then assigned to a pointer to the whole array. It might look like this:

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


The above example doesn't work. The left side looks correct to me. But I don't know what should be on the right.

My intention is to understand if it possible. And I know that there are std::vector and std::array.

UPD

Here is what I actually wanted to check:

int (*p1)[5] = (int (*)[5]) new int[5];
cout << "sizeof(*p1) = " << sizeof(*p1) << endl;

int * p2 = new int[5];
cout << "sizeof(*p2) = " << sizeof(*p2) << endl;

Answer

know that the common technique of creating a dynamic array

In C++ that was written 20 years ago, maybe.

These days you should use std::vector for dynamic arrays and std::array for fixed size array.

If your framework or platform supplies additional array classes (like QT's QVector), they are fine too, as long as you don't mess with C-pointers directly, and you have RAII-based array class.

and as for concrete answer, new T[size] always returns T* , so you cannot catch a pointer returned by new[] with T(*)[size].