我如何声明一个2d数组使用新?
比如,对于一个“普通”数组,我将:
int* ary = new int[Size]
but
int** ary = new int[sizeY][sizeX]
A)不工作/编译b)没有完成什么:
int ary[sizeY][sizeX]
所做的事。
我如何声明一个2d数组使用新?
比如,对于一个“普通”数组,我将:
int* ary = new int[Size]
but
int** ary = new int[sizeY][sizeX]
A)不工作/编译b)没有完成什么:
int ary[sizeY][sizeX]
所做的事。
当前回答
试着这样做:
int **ary = new int* [sizeY];
for (int i = 0; i < sizeY; i++)
ary[i] = new int[sizeX];
其他回答
我不确定是否没有提供以下答案 但我决定在2d数组的分配中添加一些局部优化 (例如,一个方阵只通过一次分配完成): Int ** mat = new Int *[n]; Mat [0] = new int [n * n];
然而,由于上述分配的线性,删除是这样的: 删除[]mat[0]; 删除[]mat;
这个问题一直困扰着我——这是一个很常见的问题,应该已经有了一个好的解决方案,比向量的向量或滚动你自己的数组索引更好的解决方案。
当c++中应该存在一些东西,但却不存在时,第一个地方是boost.org。在那里我找到了Boost多维数组库,multi_array。它甚至包括一个multi_array_ref类,可用于包装您自己的一维数组缓冲区。
int **arr = new int* [NoOfRows]
for(int i = 0; i<NoOfRows; i++)
arr[i] = new int[noOfColumn];
这是在c++中使用new声明2D数组的好方法 这里,NoOfRow显示了你需要多少行 ans noOfColumn显示你需要多少列
如何分配一个连续的多维数组在GNU c++ ?有一个GNU扩展允许“标准”语法工作。
问题似乎来自操作符new[]。请确保使用operator new:
double (* in)[n][n] = new (double[m][n][n]); // GNU extension
这就是全部:你得到了一个c兼容的多维数组……
在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]