How to initialize 3D array in C++ How to initialize 3D array in C++ c c

How to initialize 3D array in C++


The array in your question has only one element, so you only need one value to completely initialise it. You need three sets of braces, one for each dimension of the array.

int min[1][1][1] = {{{100}}};

A clearer example might be:

int arr[2][3][4] = { { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} },                     { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} } };

As you can see, there are two groups, each containing three groups of 4 numbers.


Instead of static multidimensional arrays you should probably use one-dimensional array and calculate the index by multiplication. E.g.

class Array3D {    size_t m_width, m_height;    std::vector<int> m_data;  public:    Array3D(size_t x, size_t y, size_t z, int init = 0):      m_width(x), m_height(y), m_data(x*y*z, init)    {}    int& operator()(size_t x, size_t y, size_t z) {        return m_data.at(x + y * m_width + z * m_width * m_height);    }};// Usage:Array3D arr(10, 15, 20, 100); // 10x15x20 array initialized with value 100arr(8, 12, 17) = 3;

std::vector allocates the storage dynamically, which is a good thing because the stack space is often very limited and 3D arrays easily use a lot of space. Wrapping it in a class like that also makes passing the array (by copy or by reference) to other functions trivial, while doing any passing of multidimensional static arrays is very problematic.

The above code is simply an example and it could be optimized and made more complete. There also certainly are existing implementations of this in various libraries, but I don't know of any.


Here's another way to dynamically allocate a 3D array in C++.

int dimX = 100; int dimY = 100; int dimZ = 100;int*** array;    // 3D array definition;// begin memory allocationarray = new int**[dimX];for(int x = 0; x < dimX; ++x) {    array[x] = new int*[dimY];    for(int y = 0; y < dimY; ++y) {        array[x][y] = new int[dimZ];        for(int z = 0; z < dimZ; ++z) { // initialize the values to whatever you want the default to be            array[x][y][z] = 0;        }    }}