c ++使用"new"或另一种创建动态数组的方法创建类似静态的数组

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

我知道在C++中使用new创建动态数组的常用技巧是:

int * arr = new int[5];

一本书还说:

short tell[10]; // tell is 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

现在我想知道是否有一种方法可以使用 new 为数组分配内存,然后可以将其分配给指向整个数组的指针。 它可能看起来像这样:

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

上面的例子不成立。左边在我看来是正确的。但是不知道右边应该放什么

我的意图是了解是否可能。我知道有 std::vectorstd::array.

更新:

这是我真正想检查的内容:

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;

下面是访问这些数组的方法:

memset(*p1, 0, sizeof(*p1));
cout << "p1[0] = " << (*p1)[0] << endl;

memset(p2, 0, sizeof(*p2) * 5);
cout << "p2[0] = " << p2[0] << endl;

know that the common technique of creating a dynamic array

在 20 年前编写的 C++ 中,也许。

现在您应该对动态数组使用 std::vector,对固定大小的数组使用 std::array

如果您的框架或平台提供额外的数组 classes(如 QT 的 QVector),它们也很好,只要您不直接弄乱 C 指针,并且您有基于 RAII 的数组 class.

至于具体的答案,new T[size] 总是 returns T* ,所以你不能用 T(*)[size].[= 捕获 new[] 返回的指针。 18=]

问题是左右瞄准具的类型不同。

类型:

new int[5]

int*.

类型:

int (*p)[5]

int (*)[5].

并且编译器不能将一个赋值给另一个。

一般来说不可能把T*赋给T (*)[N]。这就是为什么您需要使用问题开头提到的语法的原因。