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

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

int* ary = new int[Size]

but

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

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

int ary[sizeY][sizeX] 

所做的事。


当前回答

如果你想要一个2d的整数数组,它的元素在内存中是按顺序分配的,你必须像这样声明它

int (*intPtr)[n] = new int[x][n]

你可以用任何维数来代替x,但是n在两个地方必须相等。例子

int (*intPtr)[8] = new int[75][8];
intPtr[5][5] = 6;
cout<<intPtr[0][45]<<endl;

必须打印6。

其他回答

为什么不使用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(或多)维数组?

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在评论中指出的那样,这并不是一个轻量级的解决方案。另一种方法是使用一个大内存块:

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

// ary[i][j] is then rewritten as
ary[i*sizeY+j]
int **arr = new int* [NoOfRows]
for(int i = 0; i<NoOfRows; i++)
   arr[i] = new int[noOfColumn];

这是在c++中使用new声明2D数组的好方法 这里,NoOfRow显示了你需要多少行 ans noOfColumn显示你需要多少列

在c++ 11及以上版本中,我推荐两种通用技术,一种用于编译时维度,另一种用于运行时维度。这两个答案都假设您需要统一的二维数组(而不是锯齿状数组)。

编译时维度

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

同样,这仅适用于在编译时已知维度大小的情况。

运行时维度

实现只有在运行时才知道大小的二维数组的最佳方法是将其包装到一个类中。该类将分配一个1d数组,然后重载操作符[]来为第一个维度提供索引。 这是因为在c++中,2D数组是行为主的:

(摘自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(); }

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

因此,我们用std::make_unique<int[]>(行*列)项创建一个数组。我们重载操作符[],它将为我们索引行。它返回一个int *,指向该行的开头,然后可以像对列一样对该行进行解引用。注意,make_unique在c++ 14中首次发布,但如果需要,可以在c++ 11中填充它。

对于这些类型的结构,重载operator()也是很常见的:

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

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

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

问题似乎来自操作符new[]。请确保使用operator new:

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

这就是全部:你得到了一个c兼容的多维数组……