dia*_*oot 0 c++ memory arrays heap-memory
int* arr = new int[5];
指向的数组的值是否arr在堆中连续分配?
谢谢。
动态数组的正确语法是int* arr = new int[5];. 是的,它将连续分配。
这不是使用数组的推荐方式。如果您在编译时知道数组大小并且它不是太大,请将其设为本地:int arr[5];或std::array<int,5> arr;. 否则,使用std::vector<int> arr(5);. new在现代 C++ 中应该很少使用。
编辑:像这样分配的真正多维动态数组
int (*arr2)[6] = new int[5][6];
int (*arr3)[6][7] = new int[5][6][7];
Run Code Online (Sandbox Code Playgroud)
也是连续的。但是,如果您使用一维指针数组并为每个指针分配动态数组:
int** arrp = new int*[5];
for(int i=0; i<5; i++)
arrp[i] = new int[6];
Run Code Online (Sandbox Code Playgroud)
那么 data inarrp不是连续的,即使您可以像 一样使用它arr2,例如:
arrp[2][3] = 4
Run Code Online (Sandbox Code Playgroud)