三维阵列动态分配问题
problem in dynamic allocation of 3-dimensional array
array_2D = new ushort * [nx];
// Allocate each member of the "main" array
//
for (ii = 0; ii < nx; ii++)
array_2D[ii] = new ushort[ny];
// Allocate "main" array
array_3D = new ushort ** [numexp];
// Allocate each member of the "main" array
for(kk=0;kk<numexp;kk++)
array_3D[kk]= new ushort * [nx];
for(kk=0;kk<numexp;kk++)
for(ii=0;ii<nx;ii++)
array_3D[kk][ii]= new ushort[ny];
numexp,nx和ny的值由用户获取..
这是3d数组动态分配的正确形式....我们知道代码适用于2D数组…如果这是不正确的,谁能建议一个更好的方法?
我认为分配和处理多维数组的最简单方法是使用一个大的一维数组(或者最好是std::vector),并提供一个接口来正确索引。
这是最容易在二维空间中考虑的。考虑一个带有"x"answers"y"轴的二维数组
<>之前X =0 1 2Y =0 a b c我很高兴见到你。2 g h I之前我们可以用一维数组来表示,重新排列如下:
<>之前Y = 0 0 0 1 1 1 2 2 2X = 0 1 2 0 1 2 0 1 2数组:a b c d f h I之前那么我们的2d数组就是
unsigned int maxX = 0;
unsigned int maxY = 0;
std::cout << "Enter x and y dimensions":
std::cin << maxX << maxY
int array = new int[maxX*maxY];
// write to the location where x = 1, y = 2
int x = 1;
int y = 2;
array[y*maxX/*jump to correct row*/+x/*shift into correct column*/] = 0;
最重要的是将访问打包成一个简洁的接口,这样你只需要弄清楚一次
以类似的方式,我们可以处理3d数组 <>之前Z = 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2Y = 0 0 0 1 1 1 2 2 0 0 0 1 1 1 0 0 1 1 1 2 2 2X = 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2数组:a/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b/b之前一旦你弄清楚了如何正确地索引到数组,并把这段代码放在一个公共的地方,你就不必处理指针指向指针数组的指针指向指针数组的指针的麻烦了。您只需要在最后执行一次delete[]。
看起来也不错,只要arr[numexp][nx][ny]
的数组是你想要的。
一个小提示:你可以把第三维度的分配放到第二次维度的循环中,也就是说,在分配父子数组的同时分配每个第三维度:
ushort*** array_3D = new ushort**[nx];
for(int i=0; i<nx; ++i){
array_3D[i] = new ushort*[ny];
for(int j=0; j<ny; ++j)
array_3D[i][j] = new ushort[nz];
}
当然,一般的提示是:对std::vectors
这样做是为了不必处理讨厌的(de)分配问题。:)
#include <vector>
int main(){
using namespace std;
typedef unsigned short ushort;
typedef vector<ushort> usvec;
vector<vector<usvec> > my3DVector(numexp, vector<usvec>(nx, vector<ushort>(ny)));
// size of -- dimension 1 ^^^^^^ -- dimension 2 ^^ --- dimension 3 ^^
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 在C 中动态分配的内存的问题
- 有关动态分配对象的问题
- 在打印出动态分配的数组中的前两个数字时遇到问题,其他数字工作正常
- 我在动态分配结构时遇到问题
- 复制构造动态分配对象的问题
- 可以将成员变量 (CBrush *) 分配给在类构造函数中动态分配的内存,并出现新的原因问题
- ***glibc检测到***和动态分配问题-C++
- 内存堆问题C++,具有动态分配多维数组的功能
- 动态分配结构数组:赋值问题(c++)
- c++删除动态分配内存的问题
- 在c++中使用动态分配的数组有什么问题?
- 类与虚拟函数的成员对象对齐和动态分配的问题
- 基本的c++动态分配问题
- 三维阵列动态分配问题