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

比如,对于一个“普通”数组,我将:

int* ary = new int[Size]

but

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

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

int ary[sizeY][sizeX] 

所做的事。


当前回答

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

当c++中应该存在一些东西,但却不存在时,第一个地方是boost.org。在那里我找到了Boost多维数组库,multi_array。它甚至包括一个multi_array_ref类,可用于包装您自己的一维数组缓冲区。

其他回答

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

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

这是一个老答案,但我喜欢在c++中这样定义动态数组

int sizeY,sizeX = 10;
 //declaring dynamic 2d array:
    int **ary = new int*[sizeY];
    for (int i = 0; i < sizeY; i++) 
    {
     ary[i] = new int[sizeX];
   }

您可以像这样在运行时更改大小。 这是在c++ 98中测试的

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

你也可以初始化“数组”,只是给它一个默认值

const int DEFAULT = 1234;
vector< vector<int> > f(rows, vector<int>(cols, DEFAULT));

来源:如何在C/ c++中创建2,3(或多)维数组?

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

这里N是行,M是列。

动态分配

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;

打印

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];
delete [] ary;

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

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