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

时间:2021-12-28 00:42:02

How do i declare a 2d array using new?

如何使用new声明二维数组?

Like, for a "normal" array I would:

就像,对于“普通”数组,我会:

int* ary = new int[Size]

but

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

a) doesn't work/compile and b) doesn't accomplish what:

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

int ary[sizeY][sizeX] 

does.

21 个解决方案

#1


625  

A dynamic 2D array is basically an array of pointers to arrays. You can initialize it using a loop, like this:

动态2D数组基本上是指向数组的指针数组。您可以使用循环初始化它,如下所示:

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

The above, for colCount= 5 and rowCount = 4, would produce the following:

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

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

#2


271  

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

should be:

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

and then clean up would be:

然后清理将是:

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

EDIT: as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory:

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

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

#3


164  

Although this popular answer will give you your desired indexing syntax, it is doubly inefficient: big and slow both in space and time. There's a better way.

虽然这个流行的答案会为您提供所需的索引语法,但它的效率却倍增:空间和时间都很大而且很慢。还有更好的方法。

Why That Answer is Big and Slow

为什么答案很大而且很慢

The proposed solution is to create a dynamic array of pointers, then initializing each pointer to its own, independent dynamic array. The advantage of this approach is that it gives you the indexing syntax you're used to, so if you want to find the value of the matrix at position x,y, you say:

建议的解决方案是创建一个动态指针数组,然后将每个指针初始化为它自己的独立动态数组。这种方法的优点是它为您提供了您习惯的索引语法,因此如果您想在位置x,y处找到矩阵的值,您可以说:

int val = matrix[ x ][ y ];

This works because matrix[x] returns a pointer to an array, which is then indexed with [y]. Breaking it down:

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

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

Convenient, yes? We like our [ x ][ y ] syntax.

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

But the solution has a big disadvantage, which is that it is both fat and slow.

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

Why?

The reason that it's both fat and slow is actually the same. Each "row" in the matrix is a separately allocated dynamic array. Making a heap allocation is expensive both in time and space. The allocator takes time to make the allocation, sometimes running O(n) algorithms to do it. And the allocator "pads" each of your row arrays with extra bytes for bookkeeping and alignment. That extra space costs...well...extra space. The deallocator will also take extra time when you go to deallocate the matrix, painstakingly free-ing up each individual row allocation. Gets me in a sweat just thinking about it.

它既胖又慢的原因实际上是一样的。矩阵中的每个“行”是单独分配的动态数组。在时间和空间上进行堆分配都很昂贵。分配器花费时间进行分配,有时运行O(n)算法来完成分配。并且分配器为每个行数组“填充”额外的字节用于簿记和对齐。额外的空间成本......嗯...额外的空间。当您取消分配矩阵时,解除分配器也将花费额外的时间,精心地释放每个单独的行分配。只是想着它让我喘不过气来。

There's another reason it's slow. These separate allocations tend to live in discontinuous parts of memory. One row may be at address 1,000, another at address 100,000—you get the idea. This means that when you're traversing the matrix, you're leaping through memory like a wild person. This tends to result in cache misses that vastly slow down your processing time.

这是另一个原因,它很慢。这些单独的分配往往存在于不连续的内存部分。一行可能在地址1,000,另一行在地址100,000 - 您可以得到这个想法。这意味着当你遍历矩阵时,你就像一个狂野的人一样在内存中跳跃。这往往会导致缓存未命中,从而大大减慢处理时间。

So, if you absolute must have your cute [x][y] indexing syntax, use that solution. If you want quickness and smallness (and if you don't care about those, why are you working in C++?), you need a different solution.

因此,如果您绝对必须拥有可爱的[x] [y]索引语法,请使用该解决方案。如果你想要快速和小巧(如果你不关心那些,为什么你在使用C ++?),你需要一个不同的解决方案。

A Different Solution

不同的解决方案

The better solution is to allocate your whole matrix as a single dynamic array, then use (slightly) clever indexing math of your own to access cells. The indexing math is only very slightly clever; nah, it's not clever at all: it's obvious.

更好的解决方案是将整个矩阵分配为单个动态数组,然后使用(稍微)聪明的索引数学来访问单元格。索引数学只是非常聪明;不,它根本不聪明:很明显。

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

Given this index() function (which I'm imagining is a member of a class because it needs to know the m_width of your matrix), you can access cells within your matrix array. The matrix array is allocated like this:

鉴于这个index()函数(我想象它是一个类的成员,因为它需要知道矩阵的m_width),你可以访问矩阵数组中的单元格。矩阵数组的分配方式如下:

array = new int[ width * height ];

So the equivalent of this in the slow, fat solution:

所以在缓慢,肥胖的解决方案中相当于这个:

array[ x ][ y ]

...is this in the quick, small solution:

......这是一个快速,小巧的解决方案:

array[ index( x, y )]

Sad, I know. But you'll get used to it. And your CPU will thank you.

可悲,我知道。但你会习惯它。你的CPU会感谢你。

#4


98  

In C++11 it is possible:

在C ++ 11中,它是可能的:

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

This way, the memory is not initialized. To initialize it do this instead:

这样,内存不会被初始化。要初始化它,请执行以下操作:

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

Sample program (compile with "g++ -std=c++11"):

示例程序(使用“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;}

Output:

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

#5


50  

I presume from your static array example that you want a rectangular array, and not a jagged one. You can use the following:

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

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

Then you can access elements as:

然后您可以访问元素:

ary[y*sizeX + x]

Don't forget to use delete[] on ary.

别忘了在ary上使用delete []。

#6


37  

There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).

在C ++ 11及更高版本中,我建议使用两种常用技术,一种用于编译时维度,另一种用于运行时。两个答案都假设您需要均匀的二维数组(不是锯齿状的数组)。

Compile time dimensions

Use a std::array of std::array and then use new to put it on the heap:

使用std :: array的std :: array然后使用new将它放在堆上:

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

Again, this only works if the sizes of the dimensions are known at compile time.

同样,这仅在编译时已知维度的大小时才有效。

Run time dimensions

The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload operator [] to provide indexing for the first dimension. This works because in C++ a 2D array is row-major:

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

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

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

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

A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:

连续的内存序列有助于提高性能,并且易于清理。这是一个示例类,它省略了许多有用的方法,但显示了基本的想法:

#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(); }  int &operator()(size_t row, size_t column) {    return data[row * _columns + column];  }}

So we create an array with std::make_unique<int[]>(rows * columns) entries. We overload operator [] which will index the row for us. It returns an int * which points to the beginning of the row, which can then be dereferenced as normal for the column. Note that make_unique first ships in C++14 but you can polyfill it in C++11 if necessary.

所以我们用std :: make_unique (rows * columns)条目创建一个数组。我们重载operator [],它将为我们索引行。它返回一个int *,它指向行的开头,然后可以将其解除引用作为列的正常情况。请注意,make_unique首先在C ++ 14中提供,但如果需要,您可以在C ++ 11中对其进行填充。

It's also common for these types of structures to overload operator() as well:

这些类型的结构也常常重载operator():

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

Technically I haven't used new here, but it's trivial to move from std::unique_ptr<int[]> to int * and use new/delete.

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

#7


25  

This question was bugging me - it's a common enough problem that a good solution should already exist, something better than the vector of vectors or rolling your own array indexing.

这个问题困扰着我 - 这是一个很常见的问题,一个好的解决方案应该已经存在,比矢量矢量或滚动你自己的数组索引更好。

When something ought to exist in C++ but doesn't, the first place to look is boost.org. There I found the Boost Multidimensional Array Library, multi_array. It even includes a multi_array_ref class that can be used to wrap your own one-dimensional array buffer.

当C ++中存在某些东西但不存在时,首先要看的是boost.org。在那里我找到了Boost多维数组库multi_array。它甚至包括一个multi_array_ref类,可用于包装您自己的一维数组缓冲区。

#8


23  

Why not use STL:vector? So easy, and you don't need to delete the vector.

为什么不使用STL: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

#9


14  

How to allocate a contiguous multidimensional array in GNU C++? There's a GNU extension that allows the "standard" syntax to work.

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

It seems the problem come from operator new []. Make sure you use operator new instead :

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

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

And that's all : you get a C-compatible multidimensional array...

这就是全部:你得到一个C兼容的多维数组......

#10


13  

typedef is your friend

typedef是你的朋友

After going back and looking at many of the other answers I found that a deeper explanation is in order, as many of the other answers either suffer from performance problems or force you to use unusual or burdensome syntax to declare the array, or access the array elements ( or all the above ).

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

First off, this answer assumes you know the dimensions of the array at compile time. If you do, then this is the best solution as it will both give the best performance and allows you to use standard array syntax to access the array elements.

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

The reason this gives the best performance is because it allocates all of the arrays as a contiguous block of memory meaning that you are likely to have less page misses and better spacial locality. Allocating in a loop may cause the individual arrays to end up scattered on multiple non-contiguous pages through the virtual memory space as the allocation loop could be interrupted ( possibly multiple times ) by other threads or processes, or simply due to the discretion of the allocator filling in small, empty memory blocks it happens to have available.

这提供最佳性能的原因是因为它将所有数组分配为连续的内存块,这意味着您可能具有更少的页面未命中和更好的空间局部性。在循环中分配可能导致各个阵列最终分散在多个非连续页面上通过虚拟内存空间,因为分配循环可能被其他线程或进程中断(可能多次),或者仅仅由于其自行决定分配器填充小的空内存块,它恰好可用。

The other benefits are a simple declaration syntax and standard array access syntax.

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

In C++ using new:

在C ++中使用new:

#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;}

Or C style using calloc:

或使用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;}

#11


12  

A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.

2D数组基本上是一维指针数组,其中每个指针指向一维数组,该数组将保存实际数据。

Here N is row and M is column.

这里N是行,M是列。

dynamic allocation

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

fill

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

print

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

free

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

or

delete [] ary;

#12


9  

This problem has bothered me for 15 years, and all the solutions supplied weren't satisfactory for me. How do you create a dynamic multidimensional array contiguously in memory? Today I finally found the answer. Using the following code, you can do just that:

这个问题困扰了我15年,所提供的所有解决方案对我来说都不尽如人意。如何在内存中连续创建动态多维数组?今天我终于找到了答案。使用以下代码,您可以这样做:

#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;}

When you invoke the program with the values sizeX=20 and sizeY=15, the output will be the following:

当您使用值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

As you can see, the multidimensional array lies contiguously in memory, and no two memory addresses are overlapping. Even the routine for freeing the array is simpler than the standard way of dynamically allocating memory for every single column (or row, depending on how you view the array). Since the array basically consists of two linear arrays, only these two have to be (and can be) freed.

如您所见,多维数组在内存中是连续的,并且没有两个内存地址重叠。即使释放数组的例程也比为每个列(或行,根据您查看数组的方式)动态分配内存的标准方法更简单。由于阵列基本上由两个线性阵列组成,因此只有这两个必须(并且可以)被释放。

This method can be extended for more than two dimensions with the same concept. I won't do it here, but when you get the idea behind it, it is a simple task.

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

I hope this code will help you as much as it helped me.

我希望这段代码对你有所帮助。

#13


5  

Try doing this:

试着这样做:

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

#14


2  

Start by defining the array using pointers (Line 1):

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

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

#15


2  

Here, I have two options. The first one shows the concept of an array of arrays or pointer of pointers. I prefer the second one because the addresses are contiguous, as you can see in the image.

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

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

#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;}

#16


1  

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

如果您的项目是CLI(公共语言运行时支持),那么:

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.

换句话说,不是使用std命名空间和包含数组头时获得的非托管数组类,而不是std命名空间和数组头中定义的非托管数组类,而是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":

下面的代码创建了2行3列的新二维数组,类型为int,我将其命名为“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:

下面的代码访问我在上面的代码中创建的数组的第2行和第1列中的元素:

arr[0, 1]

writing only this line is to read the value in that cell, i.e. get the value in this cell, but if you add the equal = sign, you are about to write the value in that cell, i.e. 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.

只写这一行是为了读取该单元格中的值,即获取该单元格中的值,但是如果添加等号=,则即将在该单元格中写入值,即设置此单元格中的值。您当然,也可以使用+ =, - =,* =和/ =运算符,仅用于数字(int,float,double,__ int16,__ int32,__ int64等),但确定你已经知道了。

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 (i.e. size) of the array, not its rank!

如果你的项目不是CLI,那么你可以使用std命名空间的非托管数组类,如果#include ,当然,但问题是这个数组类与CLI数组不同。创建此类型的数组与CLI类似,只是您必须删除^符号和gcnew关键字。但不幸的是,<>括号中的第二个int参数指定了数组的长度(即大小),而不是它的等级!

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

没有办法在这种数组中指定排名,排名只是CLI数组的功能..

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.

std数组的行为类似于c ++中的普通数组,你用指针定义,例如int *然后:new int [size],或者没有指针:int arr [size],但不像c ++的普通数组,std数组提供可以与数组元素一起使用的函数,如fill,begin,end,size等,但普通数组不提供任何内容。

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, e.g. according to Mehrdad Afshari's idea, we can write the following code:

但仍然std数组是一维数组,就像普通的c ++数组一样。但是由于其他人提出的关于如何将普通c ++一维数组转换为二维数组的解决方案,我们可以将相同的想法调整为std数组,例如根据Mehrdad Afshari的想法,我们可以编写以下代码:

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.

这行代码创建了一个“jugged数组”,它是一个一维数组,其每个单元格指向或指向另一个一维数组。

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.

如果一维数组中的所有一维数组的长度/大小相等,那么您可以将array2d变量视为一个真正的二维数组,另外您可以使用特殊方法来处理行或列,具体取决于您查看它的方式记住,在2D数组中,std数组支持。

You also can use Kevin Loney's solution:

你也可以使用Kevin Loney的解决方案:

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

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

但是如果使用std数组,代码必须看起来不同:

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

And still have the unique functions of the std array.

并且仍然具有std数组的独特功能。

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

请注意,您仍然可以使用[]括号访问std数组的元素,并且您不必调用at函数。您还可以定义和分配新的int变量,该变量将计算并保持元素的总数。 std数组,并使用其值,而不是重复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.

您可以定义自己的二维数组泛型类,并定义二维数组类的构造函数以接收两个整数以指定新二维数组中的行数和列数,并定义接收两个整数参数的get函数访问二维数组中的元素并返回其值,并设置接收三个参数的函数,第一个是指定二维数组中行和列的整数,第三个参数是新值元件。它的类型取决于您在泛型类中选择的类型。

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#.

您将能够通过使用普通的c ++数组(指针或没有)或std数组来实现所有这些,并使用其他人建议的一个想法,并使其像cli数组一样易于使用,或者像两个您可以在C#中定义,分配和使用的维数组。

#17


1  

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].

在某些情况下,我给你留下了最适合我的解决方案。特别是如果一个人知道[数量的大小?]数组的一个维度。对于一组字符非常有用,例如,如果我们需要一个不同大小的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.

关键是数组声明中的括号。

#18


1  

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 //gusanosvoid 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;}

#19


0  

declaring 2D array dynamically:

动态声明2D数组:

    #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.

现在在上面的代码中,我们采用了一个双指针并为其分配了一个动态内存并给出了列的值。这里分配的内存仅用于列,现在我们只需要一个for循环的行,并为动态内存的每一行赋值。现在我们可以像使用2D数组一样使用指针。在上面的例子中,我们然后将随机数分配给我们的2D数组(指针)。它们都是关于2D数组的DMA。

#20


-1  

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

我在创建动态数组时使用它。如果你有一个类或结构。这很有效。例:

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;  } 

#21


-1  

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 timeint *arrayPointer = new int[3][5][]; // ** ILLEGAL **, No index can be empty int *arrayPointer = new int[][5][6]; // ** ILLEGAL **, No index can be empty

Remember:

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

1.只有第一个指数可以是一个运行时变量。其他指标必须是常数

2. NO INDEX CAN BE LEFT EMPTY.

2.没有指数可以是空的。

As mentioned in other answers, call

如其他答案所述,请致电

delete arrayPointer;

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

完成数组后释放与数组关联的内存。

#1


625  

A dynamic 2D array is basically an array of pointers to arrays. You can initialize it using a loop, like this:

动态2D数组基本上是指向数组的指针数组。您可以使用循环初始化它,如下所示:

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

The above, for colCount= 5 and rowCount = 4, would produce the following:

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

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

#2


271  

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

should be:

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

and then clean up would be:

然后清理将是:

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

EDIT: as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory:

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

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

#3


164  

Although this popular answer will give you your desired indexing syntax, it is doubly inefficient: big and slow both in space and time. There's a better way.

虽然这个流行的答案会为您提供所需的索引语法,但它的效率却倍增:空间和时间都很大而且很慢。还有更好的方法。

Why That Answer is Big and Slow

为什么答案很大而且很慢

The proposed solution is to create a dynamic array of pointers, then initializing each pointer to its own, independent dynamic array. The advantage of this approach is that it gives you the indexing syntax you're used to, so if you want to find the value of the matrix at position x,y, you say:

建议的解决方案是创建一个动态指针数组,然后将每个指针初始化为它自己的独立动态数组。这种方法的优点是它为您提供了您习惯的索引语法,因此如果您想在位置x,y处找到矩阵的值,您可以说:

int val = matrix[ x ][ y ];

This works because matrix[x] returns a pointer to an array, which is then indexed with [y]. Breaking it down:

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

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

Convenient, yes? We like our [ x ][ y ] syntax.

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

But the solution has a big disadvantage, which is that it is both fat and slow.

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

Why?

The reason that it's both fat and slow is actually the same. Each "row" in the matrix is a separately allocated dynamic array. Making a heap allocation is expensive both in time and space. The allocator takes time to make the allocation, sometimes running O(n) algorithms to do it. And the allocator "pads" each of your row arrays with extra bytes for bookkeeping and alignment. That extra space costs...well...extra space. The deallocator will also take extra time when you go to deallocate the matrix, painstakingly free-ing up each individual row allocation. Gets me in a sweat just thinking about it.

它既胖又慢的原因实际上是一样的。矩阵中的每个“行”是单独分配的动态数组。在时间和空间上进行堆分配都很昂贵。分配器花费时间进行分配,有时运行O(n)算法来完成分配。并且分配器为每个行数组“填充”额外的字节用于簿记和对齐。额外的空间成本......嗯...额外的空间。当您取消分配矩阵时,解除分配器也将花费额外的时间,精心地释放每个单独的行分配。只是想着它让我喘不过气来。

There's another reason it's slow. These separate allocations tend to live in discontinuous parts of memory. One row may be at address 1,000, another at address 100,000—you get the idea. This means that when you're traversing the matrix, you're leaping through memory like a wild person. This tends to result in cache misses that vastly slow down your processing time.

这是另一个原因,它很慢。这些单独的分配往往存在于不连续的内存部分。一行可能在地址1,000,另一行在地址100,000 - 您可以得到这个想法。这意味着当你遍历矩阵时,你就像一个狂野的人一样在内存中跳跃。这往往会导致缓存未命中,从而大大减慢处理时间。

So, if you absolute must have your cute [x][y] indexing syntax, use that solution. If you want quickness and smallness (and if you don't care about those, why are you working in C++?), you need a different solution.

因此,如果您绝对必须拥有可爱的[x] [y]索引语法,请使用该解决方案。如果你想要快速和小巧(如果你不关心那些,为什么你在使用C ++?),你需要一个不同的解决方案。

A Different Solution

不同的解决方案

The better solution is to allocate your whole matrix as a single dynamic array, then use (slightly) clever indexing math of your own to access cells. The indexing math is only very slightly clever; nah, it's not clever at all: it's obvious.

更好的解决方案是将整个矩阵分配为单个动态数组,然后使用(稍微)聪明的索引数学来访问单元格。索引数学只是非常聪明;不,它根本不聪明:很明显。

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

Given this index() function (which I'm imagining is a member of a class because it needs to know the m_width of your matrix), you can access cells within your matrix array. The matrix array is allocated like this:

鉴于这个index()函数(我想象它是一个类的成员,因为它需要知道矩阵的m_width),你可以访问矩阵数组中的单元格。矩阵数组的分配方式如下:

array = new int[ width * height ];

So the equivalent of this in the slow, fat solution:

所以在缓慢,肥胖的解决方案中相当于这个:

array[ x ][ y ]

...is this in the quick, small solution:

......这是一个快速,小巧的解决方案:

array[ index( x, y )]

Sad, I know. But you'll get used to it. And your CPU will thank you.

可悲,我知道。但你会习惯它。你的CPU会感谢你。

#4


98  

In C++11 it is possible:

在C ++ 11中,它是可能的:

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

This way, the memory is not initialized. To initialize it do this instead:

这样,内存不会被初始化。要初始化它,请执行以下操作:

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

Sample program (compile with "g++ -std=c++11"):

示例程序(使用“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;}

Output:

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

#5


50  

I presume from your static array example that you want a rectangular array, and not a jagged one. You can use the following:

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

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

Then you can access elements as:

然后您可以访问元素:

ary[y*sizeX + x]

Don't forget to use delete[] on ary.

别忘了在ary上使用delete []。

#6


37  

There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).

在C ++ 11及更高版本中,我建议使用两种常用技术,一种用于编译时维度,另一种用于运行时。两个答案都假设您需要均匀的二维数组(不是锯齿状的数组)。

Compile time dimensions

Use a std::array of std::array and then use new to put it on the heap:

使用std :: array的std :: array然后使用new将它放在堆上:

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

Again, this only works if the sizes of the dimensions are known at compile time.

同样,这仅在编译时已知维度的大小时才有效。

Run time dimensions

The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload operator [] to provide indexing for the first dimension. This works because in C++ a 2D array is row-major:

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

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

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

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

A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:

连续的内存序列有助于提高性能,并且易于清理。这是一个示例类,它省略了许多有用的方法,但显示了基本的想法:

#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(); }  int &operator()(size_t row, size_t column) {    return data[row * _columns + column];  }}

So we create an array with std::make_unique<int[]>(rows * columns) entries. We overload operator [] which will index the row for us. It returns an int * which points to the beginning of the row, which can then be dereferenced as normal for the column. Note that make_unique first ships in C++14 but you can polyfill it in C++11 if necessary.

所以我们用std :: make_unique (rows * columns)条目创建一个数组。我们重载operator [],它将为我们索引行。它返回一个int *,它指向行的开头,然后可以将其解除引用作为列的正常情况。请注意,make_unique首先在C ++ 14中提供,但如果需要,您可以在C ++ 11中对其进行填充。

It's also common for these types of structures to overload operator() as well:

这些类型的结构也常常重载operator():

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

Technically I haven't used new here, but it's trivial to move from std::unique_ptr<int[]> to int * and use new/delete.

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

#7


25  

This question was bugging me - it's a common enough problem that a good solution should already exist, something better than the vector of vectors or rolling your own array indexing.

这个问题困扰着我 - 这是一个很常见的问题,一个好的解决方案应该已经存在,比矢量矢量或滚动你自己的数组索引更好。

When something ought to exist in C++ but doesn't, the first place to look is boost.org. There I found the Boost Multidimensional Array Library, multi_array. It even includes a multi_array_ref class that can be used to wrap your own one-dimensional array buffer.

当C ++中存在某些东西但不存在时,首先要看的是boost.org。在那里我找到了Boost多维数组库multi_array。它甚至包括一个multi_array_ref类,可用于包装您自己的一维数组缓冲区。

#8


23  

Why not use STL:vector? So easy, and you don't need to delete the vector.

为什么不使用STL: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

#9


14  

How to allocate a contiguous multidimensional array in GNU C++? There's a GNU extension that allows the "standard" syntax to work.

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

It seems the problem come from operator new []. Make sure you use operator new instead :

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

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

And that's all : you get a C-compatible multidimensional array...

这就是全部:你得到一个C兼容的多维数组......

#10


13  

typedef is your friend

typedef是你的朋友

After going back and looking at many of the other answers I found that a deeper explanation is in order, as many of the other answers either suffer from performance problems or force you to use unusual or burdensome syntax to declare the array, or access the array elements ( or all the above ).

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

First off, this answer assumes you know the dimensions of the array at compile time. If you do, then this is the best solution as it will both give the best performance and allows you to use standard array syntax to access the array elements.

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

The reason this gives the best performance is because it allocates all of the arrays as a contiguous block of memory meaning that you are likely to have less page misses and better spacial locality. Allocating in a loop may cause the individual arrays to end up scattered on multiple non-contiguous pages through the virtual memory space as the allocation loop could be interrupted ( possibly multiple times ) by other threads or processes, or simply due to the discretion of the allocator filling in small, empty memory blocks it happens to have available.

这提供最佳性能的原因是因为它将所有数组分配为连续的内存块,这意味着您可能具有更少的页面未命中和更好的空间局部性。在循环中分配可能导致各个阵列最终分散在多个非连续页面上通过虚拟内存空间,因为分配循环可能被其他线程或进程中断(可能多次),或者仅仅由于其自行决定分配器填充小的空内存块,它恰好可用。

The other benefits are a simple declaration syntax and standard array access syntax.

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

In C++ using new:

在C ++中使用new:

#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;}

Or C style using calloc:

或使用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;}

#11


12  

A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.

2D数组基本上是一维指针数组,其中每个指针指向一维数组,该数组将保存实际数据。

Here N is row and M is column.

这里N是行,M是列。

dynamic allocation

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

fill

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

print

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

free

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

or

delete [] ary;

#12


9  

This problem has bothered me for 15 years, and all the solutions supplied weren't satisfactory for me. How do you create a dynamic multidimensional array contiguously in memory? Today I finally found the answer. Using the following code, you can do just that:

这个问题困扰了我15年,所提供的所有解决方案对我来说都不尽如人意。如何在内存中连续创建动态多维数组?今天我终于找到了答案。使用以下代码,您可以这样做:

#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;}

When you invoke the program with the values sizeX=20 and sizeY=15, the output will be the following:

当您使用值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

As you can see, the multidimensional array lies contiguously in memory, and no two memory addresses are overlapping. Even the routine for freeing the array is simpler than the standard way of dynamically allocating memory for every single column (or row, depending on how you view the array). Since the array basically consists of two linear arrays, only these two have to be (and can be) freed.

如您所见,多维数组在内存中是连续的,并且没有两个内存地址重叠。即使释放数组的例程也比为每个列(或行,根据您查看数组的方式)动态分配内存的标准方法更简单。由于阵列基本上由两个线性阵列组成,因此只有这两个必须(并且可以)被释放。

This method can be extended for more than two dimensions with the same concept. I won't do it here, but when you get the idea behind it, it is a simple task.

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

I hope this code will help you as much as it helped me.

我希望这段代码对你有所帮助。

#13


5  

Try doing this:

试着这样做:

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

#14


2  

Start by defining the array using pointers (Line 1):

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

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

#15


2  

Here, I have two options. The first one shows the concept of an array of arrays or pointer of pointers. I prefer the second one because the addresses are contiguous, as you can see in the image.

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

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

#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;}

#16


1  

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

如果您的项目是CLI(公共语言运行时支持),那么:

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.

换句话说,不是使用std命名空间和包含数组头时获得的非托管数组类,而不是std命名空间和数组头中定义的非托管数组类,而是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":

下面的代码创建了2行3列的新二维数组,类型为int,我将其命名为“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:

下面的代码访问我在上面的代码中创建的数组的第2行和第1列中的元素:

arr[0, 1]

writing only this line is to read the value in that cell, i.e. get the value in this cell, but if you add the equal = sign, you are about to write the value in that cell, i.e. 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.

只写这一行是为了读取该单元格中的值,即获取该单元格中的值,但是如果添加等号=,则即将在该单元格中写入值,即设置此单元格中的值。您当然,也可以使用+ =, - =,* =和/ =运算符,仅用于数字(int,float,double,__ int16,__ int32,__ int64等),但确定你已经知道了。

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 (i.e. size) of the array, not its rank!

如果你的项目不是CLI,那么你可以使用std命名空间的非托管数组类,如果#include ,当然,但问题是这个数组类与CLI数组不同。创建此类型的数组与CLI类似,只是您必须删除^符号和gcnew关键字。但不幸的是,<>括号中的第二个int参数指定了数组的长度(即大小),而不是它的等级!

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

没有办法在这种数组中指定排名,排名只是CLI数组的功能..

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.

std数组的行为类似于c ++中的普通数组,你用指针定义,例如int *然后:new int [size],或者没有指针:int arr [size],但不像c ++的普通数组,std数组提供可以与数组元素一起使用的函数,如fill,begin,end,size等,但普通数组不提供任何内容。

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, e.g. according to Mehrdad Afshari's idea, we can write the following code:

但仍然std数组是一维数组,就像普通的c ++数组一样。但是由于其他人提出的关于如何将普通c ++一维数组转换为二维数组的解决方案,我们可以将相同的想法调整为std数组,例如根据Mehrdad Afshari的想法,我们可以编写以下代码:

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.

这行代码创建了一个“jugged数组”,它是一个一维数组,其每个单元格指向或指向另一个一维数组。

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.

如果一维数组中的所有一维数组的长度/大小相等,那么您可以将array2d变量视为一个真正的二维数组,另外您可以使用特殊方法来处理行或列,具体取决于您查看它的方式记住,在2D数组中,std数组支持。

You also can use Kevin Loney's solution:

你也可以使用Kevin Loney的解决方案:

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

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

但是如果使用std数组,代码必须看起来不同:

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

And still have the unique functions of the std array.

并且仍然具有std数组的独特功能。

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

请注意,您仍然可以使用[]括号访问std数组的元素,并且您不必调用at函数。您还可以定义和分配新的int变量,该变量将计算并保持元素的总数。 std数组,并使用其值,而不是重复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.

您可以定义自己的二维数组泛型类,并定义二维数组类的构造函数以接收两个整数以指定新二维数组中的行数和列数,并定义接收两个整数参数的get函数访问二维数组中的元素并返回其值,并设置接收三个参数的函数,第一个是指定二维数组中行和列的整数,第三个参数是新值元件。它的类型取决于您在泛型类中选择的类型。

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#.

您将能够通过使用普通的c ++数组(指针或没有)或std数组来实现所有这些,并使用其他人建议的一个想法,并使其像cli数组一样易于使用,或者像两个您可以在C#中定义,分配和使用的维数组。

#17


1  

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].

在某些情况下,我给你留下了最适合我的解决方案。特别是如果一个人知道[数量的大小?]数组的一个维度。对于一组字符非常有用,例如,如果我们需要一个不同大小的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.

关键是数组声明中的括号。

#18


1  

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 //gusanosvoid 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;}

#19


0  

declaring 2D array dynamically:

动态声明2D数组:

    #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.

现在在上面的代码中,我们采用了一个双指针并为其分配了一个动态内存并给出了列的值。这里分配的内存仅用于列,现在我们只需要一个for循环的行,并为动态内存的每一行赋值。现在我们可以像使用2D数组一样使用指针。在上面的例子中,我们然后将随机数分配给我们的2D数组(指针)。它们都是关于2D数组的DMA。

#20


-1  

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

我在创建动态数组时使用它。如果你有一个类或结构。这很有效。例:

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;  } 

#21


-1  

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 timeint *arrayPointer = new int[3][5][]; // ** ILLEGAL **, No index can be empty int *arrayPointer = new int[][5][6]; // ** ILLEGAL **, No index can be empty

Remember:

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

1.只有第一个指数可以是一个运行时变量。其他指标必须是常数

2. NO INDEX CAN BE LEFT EMPTY.

2.没有指数可以是空的。

As mentioned in other answers, call

如其他答案所述,请致电

delete arrayPointer;

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

完成数组后释放与数组关联的内存。