我如何声明一个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]
所做的事。
当前回答
首先使用指针定义数组(第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
其他回答
这个问题一直困扰着我——这是一个很常见的问题,应该已经有了一个好的解决方案,比向量的向量或滚动你自己的数组索引更好的解决方案。
当c++中应该存在一些东西,但却不存在时,第一个地方是boost.org。在那里我找到了Boost多维数组库,multi_array。它甚至包括一个multi_array_ref类,可用于包装您自己的一维数组缓冲区。
如果你想要一个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。
在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]
如何分配一个连续的多维数组在GNU c++ ?有一个GNU扩展允许“标准”语法工作。
问题似乎来自操作符new[]。请确保使用operator new:
double (* in)[n][n] = new (double[m][n][n]); // GNU extension
这就是全部:你得到了一个c兼容的多维数组……
从静态数组的例子中,我假设你想要一个矩形数组,而不是锯齿形数组。你可以使用以下方法:
int *ary = new int[sizeX * sizeY];
然后你可以像这样访问元素:
ary[y*sizeX + x]
不要忘记在ary上使用delete[]。