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



我知道在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;

知道创建动态数组的常用技术

在20年前写的c++里,也许。

这些天你应该使用std::vector动态数组和std::array固定大小的数组。

如果您的框架或平台提供了额外的数组类(如QT的QVector),它们也很好,只要您不直接与c指针混淆,并且您有基于raii的数组类。

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

问题是左右视线有不同的类型。

类型:

new int[5]

int*.

类型:

int (*p)[5]

int (*)[5].

编译器不能将它们赋值给另一个

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

最新更新