C ++ creates a static array with a "new" or other way to create a dynamic array

I know that the general technique for creating a dynamic array using new in C ++ is:

 int * arr = new int[5]; 

The 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 am wondering if there is a way to allocate memory for the array using new , so it can then be assigned to a pointer to the entire array. It might look like this ::

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

The above example does not work. The left side looks right to me. But I do not know what should be on the right.

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

UPD

Here is what I really wanted to check:

 int (*p1)[5] = (int (*)[5]) new int[5]; // size of the whole array cout << "sizeof(*p1) = " << sizeof(*p1) << endl; int * p2 = new int[5]; // size of the first element cout << "sizeof(*p2) = " << sizeof(*p2) << endl; 

And here is how to access these arrays:

 memset(*p1, 0, sizeof(*p1)); cout << "p1[0] = " << (*p1)[0] << endl; memset(p2, 0, sizeof(*p2) * 5); cout << "p2[0] = " << p2[0] << endl; 
+6
source share
2 answers

know that the general method of creating a dynamic array

In C ++, which was written 20 years ago, perhaps.

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

If your infrastructure or platform provides additional array classes (for example, QT QVector ), they are also great if you do not directly associate with C pointers and you have an array class based on RAII.

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

+4
source

The problem is that the left and right views are of different types.

A type:

 new int[5] 

is an

 int*. 

A type:

 int (*p)[5] 

is an

 int (*)[5]. 

And the compiler cannot assign one to another.

In the general case, it is impossible to assign T* T (*)[N] . That is why you need to use the syntax mentioned at the beginning of your question.

+1
source

Source: https://habr.com/ru/post/1011859/


All Articles