c++ - 3维数组动态分配问题

标签 c++ arrays

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)并提供一个接口(interface)来正确索引。

这是最容易首先在二维中考虑的。考虑一个带有“x”和“y”轴的二维数组

    x=0   1   2
 y=0  a   b   c
   1  d   e   f 
   2  g   h   i

We can represent this using a 1-d array, rearranged as follows:

    y= 0 0 0 1 1 1 2 2 2
    x= 0 1 2 0 1 2 0 1 2
array: a b c d e f g h i

So our 2d array is simply

   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;

最重要的是将访问包装到一个简洁的界面中,这样您只需弄清楚一次

(以类似的方式我们可以使用 3 维数组

   z = 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2
   y = 0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 0 0 0 1 1 1 2 2 2
   x = 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2
array: a b c d e f g h i j k l m n o p q r s t u v w x

一旦您弄清楚如何正确索引数组并将此代码放在公共(public)位置,您就不必处理指向指针数组的指针到指针数组的麻烦。您只需在最后执行一次删除 []。

关于c++ - 3维数组动态分配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682564/

相关文章:

c++ - Clang5.0 : previous declaration in "__hash_table"

c++ - join() 是否释放了分配的内存? - C++11 线程

java - List<byte[]> 填充错误

javascript - 当使用 ".push"从数组生成数组时,我怎样才能更好地 "randomize"我的结果并控制重复项?

c - 为什么 [static AND] 在编译时不强制执行?

node.js - 将时间戳添加到 mongoose 中的新子文档或子模式

c++ - 将 “Extension methods support” 添加到 C++ 的错误指针分配技巧将来会成为问题吗?

c++ - boost asio iostream - 如何获取本地IP地址

c++ - 为什么这会在使用内置 qsort 时出错

c++ - 在 C 和 C++ 中通过 index[array] 访问数组