[英]Are dynamic arrays allocated contiguously in memory?
int* arr = new int[5];
Are the values of the array pointed by arr
allocated contiguously in the heap? arr
指向的数组的值是否在堆中连续分配?
Thanks.谢谢。
The right syntax for a dynamic array is int* arr = new int[5];
动态数组的正确语法是
int* arr = new int[5];
. . Yes, it will be allocated contiguously.
是的,它将连续分配。
This is not a recommended way of using an array.这不是使用数组的推荐方式。 If you know array size at compile time and it is not too large, make it local:
int arr[5];
如果您在编译时知道数组大小并且它不是太大,请将其
int arr[5];
本地: int arr[5];
or std::array<int,5> arr;
或
std::array<int,5> arr;
. . Otherwise, use
std::vector<int> arr(5);
否则,使用
std::vector<int> arr(5);
. .
new
should be rarely used in modern C++. new
在现代 C++ 中应该很少使用。
Edit: Genuine multi-dimensional dynamic arrays allocated like these编辑:像这样分配的真正多维动态数组
int (*arr2)[6] = new int[5][6];
int (*arr3)[6][7] = new int[5][6][7];
are also contiguous.也是连续的。 But if you use a 1D array of pointers and allocate dynamic array to each pointer:
但是,如果您使用一维指针数组并为每个指针分配动态数组:
int** arrp = new int*[5];
for(int i=0; i<5; i++)
arrp[i] = new int[6];
then data in arrp
is not contiguous, even though you can use it the same way as arr2
, eg:那么
arrp
数据不是连续的,即使您可以像arr2
一样使用它,例如:
arrp[2][3] = 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.