如何在C ++中使用new声明一个二维数组?

我如何使用新的声明2d数组?

就像一个“正常”的arrays,我会:

int* ary = new int[Size] 

 int** ary = new int[sizeY][sizeX] 

a)不工作/编译b)没有完成:

 int ary[sizeY][sizeX] 

确实。

dynamic2D数组基本上是指向数组的指针数组 。 您应该使用循环来初始化它,如下所示:

 int** ary = new int*[rowCount]; for(int i = 0; i < rowCount; ++i) ary[i] = new int[colCount]; 

以上,对于colCount= 5rowCount = 4 ,将产生以下内容:

在这里输入图像描述

 int** ary = new int[sizeY][sizeX] 

应该:

 int **ary = new int*[sizeY]; for(int i = 0; i < sizeY; ++i) { ary[i] = new int[sizeX]; } 

然后清理将是:

 for(int i = 0; i < sizeY; ++i) { delete [] ary[i]; } delete [] ary; 

编辑:正如Dietrich Epp在评论中指出的那样,这不是一个轻量级的解决scheme。 另一种方法是使用一大块内存:

 int *ary = new int[sizeX*sizeY]; // ary[i][j] is then rewritten as ary[i*sizeY+j] 

虽然这个stream行的答案会给你所需的索引语法,但是它是双重低效率的:在空间和时间上都大而慢。 有一个更好的方法。

为什么答案是大而慢

build议的解决scheme是创build一个dynamic数组指针,然后将每个指针初始化为它自己的独立dynamic数组。 这种方法的优点是它给了你习惯的索引语法,所以如果你想在位置x,yfindmatrix的值,你可以这样说:

 int val = matrix[ x ][ y ]; 

这是因为matrix[x]返回一个指向数组的指针,然后用[y]索引。 打破它:

 int* row = matrix[ x ]; int val = row[ y ]; 

方便,是吗? 我们喜欢我们的[x] [y]语法。

但是解决scheme有一个很大的缺点 ,那就是既胖又慢。

为什么?

它既胖又慢的原因实际上是一样的。 matrix中的每个“行”都是一个单独分配的dynamic数组。 进行堆分配在时间和空间上都是昂贵的。 分配器需要时间进行分配,有时运行O(n)algorithm来完成分配。 分配器为每个行数组添加额外的字节,用于簿记和alignment。 额外的空间成本…呃…额外的空间。 解除分配器将花费额外的时间来释放matrix,精心地释放每个单独的行分配。 给我一个汗水只是想着它。

还有另外一个原因是它很慢。 这些单独的分配倾向于生活在不连续的部分内存中。 一行可能在1000地址,另一行在10万地址 – 你明白了。 这意味着当你遍历matrix时,你就像一个狂野的人一样跨越记忆。 这往往会导致caching未命中,从而大大减慢处理时间。

所以,如果你绝对必须有你可爱的[x] [y]索引语法,那么使用这个解决scheme。 如果你想快速和小巧(如果你不关心这些,为什么你在C ++工作?),你需要一个不同的解决scheme。

不同的解决scheme

更好的解决scheme是将整个matrix分配为单个dynamic数组,然后使用(略)巧妙的索引math来访问单元格。 索引math只是非常聪明, 不,它根本不聪明:很明显。

 class Matrix { ... size_t index( int x, int y ) const { return x + m_width * y; } }; 

鉴于这个index()函数(我想像的是一个类的成员,因为它需要知道matrix的m_width ),您可以访问matrix数组中的单元格。 matrix数组像这样分配:

 array = new int[ width * height ]; 

所以相当于这个缓慢的,肥胖的解决scheme:

 array[ x ][ y ] 

…这是在快速,小解决scheme:

 array[ index( x, y )] 

伤心,我知道。 但是你会习惯的。 而你的CPU会感谢你。

在C ++ 11中有可能:

 auto array = new double[M][N]; 

这样,内存不会被初始化。 要初始化它,而不是:

 auto array = new double[M][N](); 

示例程序(用“g ++ -std = c ++ 11”编译):

 #include <iostream> #include <utility> #include <type_traits> #include <typeinfo> #include <cxxabi.h> using namespace std; int main() { const auto M = 2; const auto N = 2; // allocate (no initializatoin) auto array = new double[M][N]; // pollute the memory array[0][0] = 2; array[1][0] = 3; array[0][1] = 4; array[1][1] = 5; // re-allocate, probably will fetch the same memory block (not portable) delete[] array; array = new double[M][N]; // show that memory is not initialized for(int r = 0; r < M; r++) { for(int c = 0; c < N; c++) cout << array[r][c] << " "; cout << endl; } cout << endl; delete[] array; // the proper way to zero-initialize the array array = new double[M][N](); // show the memory is initialized for(int r = 0; r < M; r++) { for(int c = 0; c < N; c++) cout << array[r][c] << " "; cout << endl; } int info; cout << abi::__cxa_demangle(typeid(array).name(),0,0,&info) << endl; return 0; } 

输出:

 2 4 3 5 0 0 0 0 double (*) [2] 

我从你的静态数组例子,你想要一个矩形数组,而不是一个锯齿状的。 您可以使用以下内容:

 int *ary = new int[sizeX * sizeY]; 

那么你可以访问元素为:

 ary[y*sizeX + x] 

不要忘记在ary上使用delete []。

在C ++ 11及更高版本中,我会推荐两种通用技术,一种是编译时间维度,另一种是运行时间维度。 两个答案都假设你想要统一的二维数组(不是锯齿状的)。

编译时间维度

使用std::arraystd::array ,然后使用new将其放在堆上:

 // the alias helps cut down on the noise: using grid = std::array<std::array<int, sizeX> sizeY>; grid * ary = new grid; 

再说一遍,这只有在编译时已知尺寸的大小的情况下才有效。

运行时间维度

完成一个只有运行时才知道大小的2维数组的最好方法是将其包装到一个类中。 该类将分配一个1d数组,然后重载operator []为第一维提供索引。 这是有效的,因为在C ++中,二维数组是主要的行:

以逻辑形式和一维形式显示的矩阵

(取自http://eli.thegreenplace.net/2015/memory-layout-of-multi- dimensional- arrays / )

一个连续的内存序列是有利于性能的原因,也很容易清理。 下面是一个示例类,它省略了许多有用的方法,但显示了基本的想法:

 #include <memory> class Grid { size_t _rows; size_t _columns; std::unique_ptr<int[]> data; public: Grid(size_t rows, size_t columns) : _rows{rows}, _columns{columns}, data{std::make_unique<int[]>(rows * columns)} { } size_t rows() const { return _rows; } size_t columns() const { return _columns; } int * operator[] (size_t row) { return row * _columns + data.get(); } } 

所以我们用std::make_unique<int[]>(rows * columns)条目创build一个数组。 我们重载operator [] ,它将为我们索引行。 它返回一个int * ,然后可以像正常那样对列进行解引用。 请注意, make_unique首先在C ++ 14中发布,但如果需要,您可以在C ++ 11中对其进行make_unique

对于这些types的结构来说也重载operator()也是很常见的:

  int & operator() (size_t row, size_t column) { return data[row * _columns + column]; } 

从技术上讲,我没有在这里使用new ,但从std::unique_ptr<int[]>移到int *并使用new / delete是微不足道的。

这个问题正在困扰我 – 这是一个普遍的问题,一个好的解决scheme应该已经存在,比向量vector或滚动自己的数组索引更好。

当C ++中应该存在某些东西时,首先要看的是boost.org 。 在那里,我find了Boost Multidimensional Array Library, multi_array 。 它甚至包括一个multi_array_ref类,可以用来包装你自己的一维数组缓冲区。

为什么不使用STL:vector? 很简单,你不需要删除vector。

 int rows = 100; int cols = 200; vector< vector<int> > f(rows, vector<int>(cols)); f[rows - 1][cols - 1] = 0; // use it like arrays 

如何在GNU C ++中分配一个连续的multidimensional array? 有一个允许“标准”语法工作的GNU扩展。

看来问题来自operator new []。 确保你使用operator new来代替:

 double (* in)[n][n] = new (double[m][n][n]); // GNU extension 

就是这样:你得到一个C兼容的multidimensional array…

我build议阅读C ++ FAQ Lite在这个主题上的说明。 使用new分配(更重要的是,正确释放)multidimensional array可能会非常棘手。 此外,从我链接的下一个三个常见问题解答是一个很好的阅读。 他们会给你提示如何把你的数组变成自己的类(启用RAII等),以及使用模板进行通用性的介绍。

typedef是你的朋友

回头看看许多其他答案后,我发现更深的解释是为了顺序,因为许多其他的答案要么遇到性能问题,要么迫使你使用不寻常的或繁琐的语法来声明数组,或访问数组元素(或以上所有)。

首先,这个答案假定你知道在编译时数组的维数。 如果你这样做,那么这是最好的解决scheme,因为它将提供最好的性能,并允许你使用标准的数组语法来访问数组元素

这样可以获得最佳性能的原因是因为它将所有数组分配为一个连续的内存块,这意味着您可能有较less的页面丢失和更好的空间局部性。 在循环中分配可能导致单个数组通过虚拟内存空间分散在多个不连续的页面上,因为分配循环可能被其他线程或进程中断(可能多次),或者简单地由于分配器填充小的,空的内存块它恰好有可用。

其他好处是一个简单的声明语法和标准的数组访问语法。

在C ++中使用新的:

 #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { typedef double (array5k_t)[5000]; array5k_t *array5k = new array5k_t[5000]; array5k[4999][4999] = 10; printf("array5k[4999][4999] == %f\n", array5k[4999][4999]); return 0; } 

或使用calloc的C风格:

 #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { typedef double (*array5k_t)[5000]; array5k_t array5k = calloc(5000, sizeof(double)*5000); array5k[4999][4999] = 10; printf("array5k[4999][4999] == %f\n", array5k[4999][4999]); return 0; } 

二维数组基本上是一个一维数组指针,其中每个指针都指向一维数组,它将保存实际的数据。

这里N是行,M是列。

dynamic分配

 int** ary = new int*[N]; for(int i = 0; i < N; i++) ary[i] = new int[M]; 

 for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) ary[i][j] = i; 

打印

 for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) std::cout << ary[i][j] << "\n"; 

自由

 for(int i = 0; i < N; i++) delete [] ary[i]; 

要么

 delete [] ary; 

尝试这样做:

 int **ary = new int[sizeY]; for (int i = 0; i < sizeY; i++) ary[i] = new int[sizeX]; 

这个问题困扰了我15年,所提供的所有解决scheme都不尽如人意。 如何在内存中创build一个连续的dynamicmultidimensional array。 今天我终于find了答案。 使用下面的代码,你可以做到这一点:

 #include <iostream> int main(int argc, char** argv) { if (argc != 3) { std::cerr << "You have to specify the two array dimensions" << std::endl; return -1; } int sizeX, sizeY; sizeX = std::stoi(argv[1]); sizeY = std::stoi(argv[2]); if (sizeX <= 0) { std::cerr << "Invalid dimension x" << std::endl; return -1; } if (sizeY <= 0) { std::cerr << "Invalid dimension y" << std::endl; return -1; } /******** Create a two dimensional dynamic array in continuous memory ****** * * - Define the pointer holding the array * - Allocate memory for the array (linear) * - Allocate memory for the pointers inside the array * - Assign the pointers inside the array the corresponding addresses * in the linear array **************************************************************************/ // The resulting array unsigned int** array2d; // Linear memory allocation unsigned int* temp = new unsigned int[sizeX * sizeY]; // These are the important steps: // Allocate the pointers inside the array, // which will be used to index the linear memory array2d = new unsigned int*[sizeY]; // Let the pointers inside the array point to the correct memory addresses for (int i = 0; i < sizeY; ++i) { array2d[i] = (temp + i * sizeX); } // Fill the array with ascending numbers for (int y = 0; y < sizeY; ++y) { for (int x = 0; x < sizeX; ++x) { array2d[y][x] = x + y * sizeX; } } // Code for testing // Print the addresses for (int y = 0; y < sizeY; ++y) { for (int x = 0; x < sizeX; ++x) { std::cout << std::hex << &(array2d[y][x]) << ' '; } } std::cout << "\n\n"; // Print the array for (int y = 0; y < sizeY; ++y) { std::cout << std::hex << &(array2d[y][0]) << std::dec; std::cout << ": "; for (int x = 0; x < sizeX; ++x) { std::cout << array2d[y][x] << ' '; } std::cout << std::endl; } // Free memory delete[] array2d[0]; delete[] array2d; array2d = nullptr; return 0; } 

当您使用sizeX = 20和sizeY = 15的值调用程序时,输出将如下所示:

 0x603010 0x603014 0x603018 0x60301c 0x603020 0x603024 0x603028 0x60302c 0x603030 0x603034 0x603038 0x60303c 0x603040 0x603044 0x603048 0x60304c 0x603050 0x603054 0x603058 0x60305c 0x603060 0x603064 0x603068 0x60306c 0x603070 0x603074 0x603078 0x60307c 0x603080 0x603084 0x603088 0x60308c 0x603090 0x603094 0x603098 0x60309c 0x6030a0 0x6030a4 0x6030a8 0x6030ac 0x6030b0 0x6030b4 0x6030b8 0x6030bc 0x6030c0 0x6030c4 0x6030c8 0x6030cc 0x6030d0 0x6030d4 0x6030d8 0x6030dc 0x6030e0 0x6030e4 0x6030e8 0x6030ec 0x6030f0 0x6030f4 0x6030f8 0x6030fc 0x603100 0x603104 0x603108 0x60310c 0x603110 0x603114 0x603118 0x60311c 0x603120 0x603124 0x603128 0x60312c 0x603130 0x603134 0x603138 0x60313c 0x603140 0x603144 0x603148 0x60314c 0x603150 0x603154 0x603158 0x60315c 0x603160 0x603164 0x603168 0x60316c 0x603170 0x603174 0x603178 0x60317c 0x603180 0x603184 0x603188 0x60318c 0x603190 0x603194 0x603198 0x60319c 0x6031a0 0x6031a4 0x6031a8 0x6031ac 0x6031b0 0x6031b4 0x6031b8 0x6031bc 0x6031c0 0x6031c4 0x6031c8 0x6031cc 0x6031d0 0x6031d4 0x6031d8 0x6031dc 0x6031e0 0x6031e4 0x6031e8 0x6031ec 0x6031f0 0x6031f4 0x6031f8 0x6031fc 0x603200 0x603204 0x603208 0x60320c 0x603210 0x603214 0x603218 0x60321c 0x603220 0x603224 0x603228 0x60322c 0x603230 0x603234 0x603238 0x60323c 0x603240 0x603244 0x603248 0x60324c 0x603250 0x603254 0x603258 0x60325c 0x603260 0x603264 0x603268 0x60326c 0x603270 0x603274 0x603278 0x60327c 0x603280 0x603284 0x603288 0x60328c 0x603290 0x603294 0x603298 0x60329c 0x6032a0 0x6032a4 0x6032a8 0x6032ac 0x6032b0 0x6032b4 0x6032b8 0x6032bc 0x6032c0 0x6032c4 0x6032c8 0x6032cc 0x6032d0 0x6032d4 0x6032d8 0x6032dc 0x6032e0 0x6032e4 0x6032e8 0x6032ec 0x6032f0 0x6032f4 0x6032f8 0x6032fc 0x603300 0x603304 0x603308 0x60330c 0x603310 0x603314 0x603318 0x60331c 0x603320 0x603324 0x603328 0x60332c 0x603330 0x603334 0x603338 0x60333c 0x603340 0x603344 0x603348 0x60334c 0x603350 0x603354 0x603358 0x60335c 0x603360 0x603364 0x603368 0x60336c 0x603370 0x603374 0x603378 0x60337c 0x603380 0x603384 0x603388 0x60338c 0x603390 0x603394 0x603398 0x60339c 0x6033a0 0x6033a4 0x6033a8 0x6033ac 0x6033b0 0x6033b4 0x6033b8 0x6033bc 0x6033c0 0x6033c4 0x6033c8 0x6033cc 0x6033d0 0x6033d4 0x6033d8 0x6033dc 0x6033e0 0x6033e4 0x6033e8 0x6033ec 0x6033f0 0x6033f4 0x6033f8 0x6033fc 0x603400 0x603404 0x603408 0x60340c 0x603410 0x603414 0x603418 0x60341c 0x603420 0x603424 0x603428 0x60342c 0x603430 0x603434 0x603438 0x60343c 0x603440 0x603444 0x603448 0x60344c 0x603450 0x603454 0x603458 0x60345c 0x603460 0x603464 0x603468 0x60346c 0x603470 0x603474 0x603478 0x60347c 0x603480 0x603484 0x603488 0x60348c 0x603490 0x603494 0x603498 0x60349c 0x6034a0 0x6034a4 0x6034a8 0x6034ac 0x6034b0 0x6034b4 0x6034b8 0x6034bc 0x603010: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0x603060: 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 0x6030b0: 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 0x603100: 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 0x603150: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 0x6031a0: 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 0x6031f0: 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 0x603240: 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 0x603290: 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 0x6032e0: 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 0x603330: 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 0x603380: 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 0x6033d0: 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 0x603420: 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 0x603470: 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 

正如你所看到的,multidimensional array在内存中是连续的,没有两个内存地址重叠。 即使是释放数组的例程比为每一列(或行,根据查看数组的方式)dynamic分配内存的标准方式简单。 由于数组基本上由两个线性数组组成,因此只有这两个数组必须是(并且可以)被释放。

这个方法可以用相同的概念扩展到两个以上的维度。 我不会在这里做,但是当你明白这个想法时,这是一个简单的任务。

我希望这个代码能够帮助你,就像帮助我一样。

首先使用指针定义数组(第一行):

 int** a = new int* [x]; //x is the number of rows for(int i = 0; i < x; i++) a[i] = new int[y]; //y is the number of columns 

在这里,我有两个select。 第一个显示了数组或数组指针的指针的概念。 我更喜欢第二个,因为地址是连续的,就像你在图像中看到的那样。

在这里输入图像描述

 #include <iostream> using namespace std; int main(){ int **arr_01,**arr_02,i,j,rows=4,cols=5; //Implementation 1 arr_01=new int*[rows]; for(int i=0;i<rows;i++) arr_01[i]=new int[cols]; for(i=0;i<rows;i++){ for(j=0;j<cols;j++) cout << arr_01[i]+j << " " ; cout << endl; } for(int i=0;i<rows;i++) delete[] arr_01[i]; delete[] arr_01; cout << endl; //Implementation 2 arr_02=new int*[rows]; arr_02[0]=new int[rows*cols]; for(int i=1;i<rows;i++) arr_02[i]=arr_02[0]+cols*i; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++) cout << arr_02[i]+j << " " ; cout << endl; } delete[] arr_02[0]; delete[] arr_02; return 0; } 

If your project is CLI (Common Language Runtime Support) , then:

You can use the array class, not that one you get when you write:

 #include <array> using namespace std; 

In other words, not the unmanaged array class you get when using the std namespace and when including the array header, not the unmanaged array class defined in the std namespace and in the array header, but the managed class array of the CLI.

with this class, you can create an array of any rank you want.

The following code below creates new two dimensional array of 2 rows and 3 columns and of type int, and I name it "arr":

 array<int, 2>^ arr = gcnew array<int, 2>(2, 3); 

Now you can access elements in the array, by name it and write only one squared parentheses [] , and inside them, add the row and column, and separate them with the comma , .

The following code below access an element in 2nd row and 1st column of the array I already created in previous code above:

 arr[0, 1] 

writing only this line is to read the value in that cell, ie get the value in this cell, but if you add the equal = sign, you are about to write the value in that cell, ie set the value in this cell. You also can use the +=, -=, *= and /= operators of course, for numbers only (int, float, double, __int16, __int32, __int64 and etc), but sure you know it already.

If your project is not CLI, then you can use the unmanaged array class of the std namespace, if you #include <array> , of course, but the problem is that this array class is different than the CLI array. Create array of this type is same like the CLI, except that you will have to remove the ^ sign and the gcnew keyword. But unfortunately the second int parameter in the <> parentheses specifies the length (ie size) of the array, not its rank!

There is no way to specify rank in this kind of array, rank is CLI array's feature only.

std array behaves like normal array in c++, that you define with pointer, for example int* and then: new int[size] , or without pointer: int arr[size] , but unlike the normal array of the c++, std array provides functions that you can use with the elements of the array, like fill, begin, end, size, and etc, but normal array provides nothing .

But still std array are one dimensional array, like the normal c++ arrays. But thanks to the solutions that the other guys suggest about how you can make the normal c++ one dimensional array to two dimensional array, we can adapt the same ideas to std array, eg according to Mehrdad Afshari's idea, we can write the following code:

 array<array<int, 3>, 2> array2d = array<array<int, 3>, 2>(); 

This line of code creates a "jugged array" , which is an one dimensional array that each of its cells is or points to another one dimensional array.

If all one dimensional arrays in one dimensional array are equal in their length/size, then you can treat the array2d variable as a real two dimensional array, plus you can use the special methods to treat rows or columns, depends on how you view it in mind, in the 2D array, that std array supports.

You also can use Kevin Loney's solution:

 int *ary = new int[sizeX*sizeY]; // ary[i][j] is then rewritten as ary[i*sizeY+j] 

but if you use std array, the code must look different:

 array<int, sizeX*sizeY> ary = array<int, sizeX*sizeY>(); ary.at(i*sizeY+j); 

And still have the unique functions of the std array.

Note that you still can access the elements of the std array using the [] parentheses, and you don't have to call the at function. You also can define and assign new int variable that will calculate and keep the total number of elements in the std array, and use its value, instead of repeating sizeX*sizeY

You can define your own two dimensional array generic class, and define the constructor of the two dimensional array class to receive two integers to specify the number of rows and columns in the new two dimensional array, and define get function that receive two parameters of integer that access an element in the two dimensional array and returns its value, and set function that receives three parameters, that the two first are integers that specify the row and column in the two dimensional array, and the third parameter is the new value of the element. Its type depends on the type you chose in the generic class.

You will be able to implement all this by using either the normal c++ array (pointers or without) or the std array and use one of the ideas that other people suggested, and make it easy to use like the cli array, or like the two dimensional array that you can define, assign and use in C#.

I have left you with a solution which works the best for me, in certain cases. Especially if one knows [the size of?] one dimension of the array. Very useful for an array of chars, for instance if we need an array of varying size of arrays of char[20].

 int size = 1492; char (*array)[20]; array = new char[size][20]; ... strcpy(array[5], "hola!"); ... delete [] array; 

The key is the parentheses in the array declaration.

I used this not elegant but FAST,EASY and WORKING system. I do not see why can not work because the only way for the system to allow create a big size array and access parts is without cutting it in parts:

 #define DIM 3 #define WORMS 50000 //gusanos void halla_centros_V000(double CENW[][DIM]) { CENW[i][j]=... ... } int main() { double *CENW_MEM=new double[WORMS*DIM]; double (*CENW)[DIM]; CENW=(double (*)[3]) &CENW_MEM[0]; halla_centros_V000(CENW); delete[] CENW_MEM; } 

declaring 2D array dynamically:

  #include<iostream> using namespace std; int main() { int x = 3, y = 3; int **ptr = new int *[x]; for(int i = 0; i<y; i++) { ptr[i] = new int[y]; } srand(time(0)); for(int j = 0; j<x; j++) { for(int k = 0; k<y; k++) { int a = rand()%10; ptr[j][k] = a; cout<<ptr[j][k]<<" "; } cout<<endl; } } 

Now in the above code we took a double pointer and assigned it a dynamic memory and gave a value of the columns. Here the memory allocated is only for the columns, now for the rows we just need a for loop and assign the value for every row a dynamic memory. Now we can use the pointer just the way we use a 2D array. In the above example we then assigned random numbers to our 2D array(pointer).Its all about DMA of 2D array.

I'm using this when creating dynamic array. If you have a class or a struct. And this works. 例:

 struct Sprite { int x; }; int main () { int num = 50; Sprite **spritearray;//a pointer to a pointer to an object from the Sprite class spritearray = new Sprite *[num]; for (int n = 0; n < num; n++) { spritearray[n] = new Sprite; spritearray->x = n * 3; } //delete from random position for (int n = 0; n < num; n++) { if (spritearray[n]->x < 0) { delete spritearray[n]; spritearray[n] = NULL; } } //delete the array for (int n = 0; n < num; n++) { if (spritearray[n] != NULL){ delete spritearray[n]; spritearray[n] = NULL; } } delete []spritearray; spritearray = NULL; return 0; } 

This is not the one in much details, but quite simplified.

 int *arrayPointer = new int[4][5][6]; // ** LEGAL** int *arrayPointer = new int[m][5][6]; // ** LEGAL** m will be calculated at run time int *arrayPointer = new int[3][5][]; // ** ILLEGAL **, No index can be empty int *arrayPointer = new int[][5][6]; // ** ILLEGAL **, No index can be empty 

记得:

1. ONLY THE THE FIRST INDEX CAN BE A RUNTIME VARIABLE. OTHER INDEXES NEED TO BE CONSTANT

2. NO INDEX CAN BE LEFT EMPTY.

As mentioned in other answers, call

 delete arrayPointer; 

to deallocate memory associated with the array when you are done with the array.