我知道在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;
int (*p)[5] =
еҲҶй…ҚеҶ…еӯҳпјҢеҜ№еҗ—пјҹ - Kostiantyn Ponomarenko(int(*)[5])new int[5]
,但请不要在实际代码中这样做。 - David Haim