我知道在 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::vector
和 std::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
用于固定大小的数组。
如果您的框架或平台提供额外的数组类(如 QT 的 QVector
),它们也很好,只要您不直接弄乱 C 指针,并且您有基于 RAII 的数组类。
至于具体答案,new T[size]
总是返回 T*
,所以你不能捕获 new[]
返回的指针> 使用 T(*)[size]
。
关于C++ 使用 "new"创建静态类数组或创建动态数组的另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330178/