Chris_45
Chris_45

Reputation: 9063

How to initialize 3D array in C++

How do you initialize a 3d array in C++

int min[1][1][1] = {100, { 100, {100}}}; //this is not the way

Upvotes: 41

Views: 99120

Answers (4)

Kenny Cason
Kenny Cason

Reputation: 12328

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 allocation
array = 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;
        }
    }
}

Upvotes: 10

Potatoswatter
Potatoswatter

Reputation: 137920

Everyone seems to forget std::valarray. It's the STL template for flat multidimensional arrays, and indexing and slicing them.

http://www.cplusplus.com/reference/std/valarray/

No static initialization, but is that really essential?

Upvotes: 3

Carl Norum
Carl Norum

Reputation: 225162

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.

Upvotes: 69

Tronic
Tronic

Reputation: 10430

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 100
arr(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.

Upvotes: 10

Related Questions