<p>I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using <code>STL</code> techniques such as vectors.</p>

<p>Essentially I want my integer array dimensions to look like:</p>

<pre><code>[ x ][ y ][ z ]
</code></pre>

<p>x and y are in the range 20-6000
z is known and equals 4.</p>

[{'answer_id': 62532, 'author': 'ChrisN', 'author_id': 3853, 'author_profile': 'https://Stackoverflow.com/users/3853', 'pm_score': 5, 'selected': True, 'text': '<p>Have a look at the Boost <a href="http://www.boost.org/doc/libs/release/libs/multi_array" rel="noreferrer">multi-dimensional array</a> library. Here\'s an example (adapted from the Boost documentation):</p>\n\n<pre><code>#include "boost/multi_array.hpp"\n\nint main() {\n  // Create a 3D array that is 20 x 30 x 4\n  int x = 20;\n  int y = 30;\n  int z = 4;\n\n  typedef boost::multi_array&lt;int, 3&gt; array_type;\n  typedef array_type::index index;\n  array_type my_array(boost::extents[x][y][z]);\n\n  // Assign values to the elements\n  int values = 0;\n  for (index i = 0; i != x; ++i) {\n    for (index j = 0; j != y; ++j) {\n      for (index k = 0; k != z; ++k) {\n        my_array[i][j][k] = values++;\n      }\n    }\n  }\n}\n</code></pre>\n'}, {'answer_id': 62601, 'author': 'Zooba', 'author_id': 891, 'author_profile': 'https://Stackoverflow.com/users/891', 'pm_score': 3, 'selected': False, 'text': "<p>Each pair of square brackets is a dereferencing operation (when applied to a pointer). As an example, the following pairs of lines of code are equivalent:</p>\n\n<pre><code>x = myArray[4];\nx = *(myArray+4);\n</code></pre>\n\n<p>&nbsp;</p>\n\n<pre><code>x = myArray[2][7];\nx = *((*(myArray+2))+7);\n</code></pre>\n\n<p>To use your suggested syntax you are simply dereferencing the value returned from the first dereference.</p>\n\n<pre><code>int*** myArray = (some allocation method, keep reading);\n//\n// All in one line:\nint   value = myArray[x][y][z];\n//\n// Separated to multiple steps:\nint** deref1 = myArray[x];\nint*  deref2 = deref1[y];\nint   value = deref2[z];\n</code></pre>\n\n<p>To go about allocating this array, you simply need to recognise that you don't actually have a three-dimensional array of integers. You have an array of arrays of arrays of integers.</p>\n\n<pre><code>// Start by allocating an array for array of arrays\nint*** myArray = new int**[X_MAXIMUM];\n\n// Allocate an array for each element of the first array\nfor(int x = 0; x &lt; X_MAXIMUM; ++x)\n{\n    myArray[x] = new int*[Y_MAXIMUM];\n\n    // Allocate an array of integers for each element of this array\n    for(int y = 0; y &lt; Y_MAXIMUM; ++y)\n    {\n        myArray[x][y] = new int[Z_MAXIMUM];\n\n        // Specify an initial value (if desired)\n        for(int z = 0; z &lt; Z_MAXIMUM; ++z)\n        {\n            myArray[x][y][z] = -1;\n        }\n    }\n}\n</code></pre>\n\n<p>Deallocating this array follows a similar process to allocating it:</p>\n\n<pre><code>for(int x = 0; x &lt; X_MAXIMUM; ++x)\n{\n    for(int y = 0; y &lt; Y_MAXIMUM; ++y)\n    {\n        delete[] myArray[x][y];\n    }\n\n    delete[] myArray[x];\n}\n\ndelete[] myArray;\n</code></pre>\n"}, {'answer_id': 62659, 'author': 'Mark Webster', 'author_id': 7068, 'author_profile': 'https://Stackoverflow.com/users/7068', 'pm_score': 1, 'selected': False, 'text': "<p>It should be noted that, for all intents and purposes, you are dealing with only a 2D array, because the third (and least significant) dimension is known.</p>\n\n<p>Using the STL or Boost are quite good approaches if you don't know beforehand how many entries you will have in each dimension of the array, because they will give you dynamic memory allocation, and I recommend either of these approaches if your data set is to remain largely static, or if it to mostly only receive new entries and not many deletions.</p>\n\n<p>However, if you know something about your dataset beforehand, such as roughly how many items in total will be stored, or if the arrays are to be sparsely populated, you might be better off using some kind of hash/bucket function, and use the XYZ indices as your key. In this case, assuming no more than 8192 (13 bits) entries per dimension, you could get by with a 40-bit (5-byte) key. Or, assuming there are always 4 x Z entries, you would simply use a 26-bit XY key. This is one of the more efficient trade-offs between speed, memory usage, and dynamic allocation.</p>\n"}, {'answer_id': 62674, 'author': 'Pieter', 'author_id': 5822, 'author_profile': 'https://Stackoverflow.com/users/5822', 'pm_score': 2, 'selected': False, 'text': '<p>With vectors:</p>\n\n<pre><code>std::vector&lt; std::vector&lt; std::vector&lt; int &gt; &gt; &gt; array3d;\n</code></pre>\n\n<p>Every element is accessible wit array3d[x][y][z] if the element was already added. (e.g. via push_back)</p>\n'}, {'answer_id': 62915, 'author': 'Paul Troon', 'author_id': 6649, 'author_profile': 'https://Stackoverflow.com/users/6649', 'pm_score': 1, 'selected': False, 'text': "<p>There are many advantages to using the STL to manage your memory over using new/delete.  The choice of how to represent your data depends on how you plan to use it.  One suggestion would be a class that hides the implementation decision and provides three dimensional get/set methods to a one dimensional STL vector.  </p>\n\n<p>If you really believe you need to create a custom 3d vector type, investigate Boost first.</p>\n\n<pre><code>// a class that does something in 3 dimensions\n\nclass MySimpleClass\n{\npublic:\n\n  MySimpleClass(const size_t inWidth, const size_t inHeight, const size_t inDepth) :\n   mWidth(inWidth), mHeight(inHeight), mDepth(inDepth)\n   {\n       mArray.resize(mWidth * mHeight * mDepth);\n   }\n\n\n  // inline for speed\n  int Get(const size_t inX, const size_t inY, const size_t inZ) {\n     return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];\n  }\n\n  void Set(const size_t inX, const size_t inY, const size_t inZ, const int inVal) {\n     return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];\n  }\n\n  // doing something uniform with the data is easier if it's not a vector of vectors\n  void DoSomething()\n  {\n     std::transform(mArray.begin(), mArray.end(), mArray.begin(), MyUnaryFunc);\n  }\n\nprivate:\n\n  // dimensions of data\n  size_t mWidth;\n  size_t mHeight;\n  size_t mDepth;\n\n  // data buffer\n  std::vector&lt; int &gt; mArray;\n};\n</code></pre>\n"}, {'answer_id': 63541, 'author': 'yrp', 'author_id': 7228, 'author_profile': 'https://Stackoverflow.com/users/7228', 'pm_score': -1, 'selected': False, 'text': "<p>Pieter's suggestion is good of course, but one thing you've to bear in mind is that in case of big arrays building it may be quite slow. Every time vector capacity changes, all the data has to be copied around ('n' vectors of vectors).</p>\n"}, {'answer_id': 4466150, 'author': 'kriss', 'author_id': 168465, 'author_profile': 'https://Stackoverflow.com/users/168465', 'pm_score': 3, 'selected': False, 'text': '<p>Below is a straightforward way to create 3D arrays using C or C++ in one chunk of memory for each array. No need to use BOOST (even if it\'s nice), or to split allocation between lines with multiple indirection (this is quite bad as it usually gives big performance penalty when accessing data and it fragments memory).</p>\n\n<p>The only thing to understand is that there is no such thing as multidimensional arrays, just arrays of arrays (of arrays). The innermost index being the farthest in memory.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(){\n\n    {\n        // C Style Static 3D Arrays\n        int a[10][20][30];\n        a[9][19][29] = 10;\n        printf("a[9][19][29]=%d\\n", a[9][19][29]);\n    }\n\n    {\n        // C Style dynamic 3D Arrays\n        int (*a)[20][30];\n        a = (int (*)[20][30])malloc(10*20*30*sizeof(int));\n        a[9][19][29] = 10;\n        printf("a[9][19][29]=%d\\n", a[9][19][29]);\n        free(a);\n    }\n\n    {\n        // C++ Style dynamic 3D Arrays\n        int (*a)[20][30];\n        a = new int[10][20][30];\n        a[9][19][29] = 10;\n        printf("a[9][19][29]=%d\\n", a[9][19][29]);\n        delete [] a;\n    }\n\n}\n</code></pre>\n\n<p>For your actual problem, as there potentially is two unknown dimensions, there is a problem with my proposal at it allow only one unknown dimension. There is several ways to manage that.</p>\n\n<p>The good news is that using variables now works with C, it is called variable length arrays. You look <a href="http://www.drdobbs.com/184401444;jsessionid=LAEWOLZQCC2AJQE1GHPSKH4ATMY32JVN" rel="noreferrer">here</a> for details.</p>\n\n<pre><code>    int x = 100;\n    int y = 200;\n    int z = 30;\n\n    {\n        // C Style Static 3D Arrays \n        int a[x][y][z];\n        a[99][199][29] = 10;\n        printf("a[99][199][29]=%d\\n", a[99][199][29]);\n    }\n\n    {\n        // C Style dynamic 3D Arrays\n        int (*a)[y][z];\n        a = (int (*)[y][z])malloc(x*y*z*sizeof(int));\n        a[99][199][29] = 10;\n        printf("a[99][199][29]=%d\\n", a[99][199][29]);\n        free(a);\n    }\n</code></pre>\n\n<p>If using C++ the simplest way is probably to use operator overloading to stick with array syntax:</p>\n\n<pre><code>    {\n        class ThreeDArray {\n            class InnerTwoDArray {\n                int * data;\n                size_t y;\n                size_t z;\n                public:\n                InnerTwoDArray(int * data, size_t y, size_t z)\n                    : data(data), y(y), z(z) {}\n\n                public:\n                int * operator [](size_t y){ return data + y*z; }\n            };\n\n            int * data;\n            size_t x;\n            size_t y;\n            size_t z;\n            public:\n            ThreeDArray(size_t x, size_t y, size_t z) : x(x), y(y), z(z) {\n                data = (int*)malloc(x*y*z*sizeof data);\n            }\n\n            ~ThreeDArray(){ free(data); }\n\n            InnerTwoDArray operator [](size_t x){\n                return InnerTwoDArray(data + x*y*z, y, z);\n            }\n        };\n\n        ThreeDArray a(x, y, z);\n        a[99][199][29] = 10;\n        printf("a[99][199][29]=%d\\n", a[99][199][29]);\n    }\n</code></pre>\n\n<p>The above code has some indirection cost for accessing InnerTwoDArray (but a good compiler can probably optimize it away) but uses only one memory chunk for array allocated on heap. Which is usually the most efficient choice.</p>\n\n<p>Obviously even if the above code is still simple and straightforward, STL or BOOST does it well, hence no need to reinvent the wheel. I still believe it is interesting to know it can be easily done.</p>\n'}]
['https://Stackoverflow.com/questions/62512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6795/']