c ++使用"new"或其他创建动态数组的方法创建静态类数组

Kos*_*nko 6 c++ arrays pointers new-operator

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

int * arr = new int[5];
Run Code Online (Sandbox Code Playgroud)

一本书还说:

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
Run Code Online (Sandbox Code Playgroud)

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

int (*p)[5] = new int[5]; 
Run Code Online (Sandbox Code Playgroud)

上面的例子不起作用.左边看起来对我来说正确.但我不知道右边应该是什么.

我的目的是了解它是否可行.我知道有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;
Run Code Online (Sandbox Code Playgroud)

以下是如何访问这些数组:

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

memset(p2, 0, sizeof(*p2) * 5);
cout << "p2[0] = " << p2[0] << endl;
Run Code Online (Sandbox Code Playgroud)

Dav*_*aim 4

了解创建动态数组的常用技术

也许是 20 年前用 C++ 编写的。

如今,您应该用于std::vector动态数组和std::array固定大小数组。

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

至于具体答案,new T[size]总是返回,因此您无法捕获withT*返回的指针。new[]T(*)[size]

  • 您可以使用 c-cast `(int(*)[5])new int[5]` 强制转换它,但请不要在实际代码中执行此操作。 (2认同)