42

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

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

5 Answers 5

69

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need nested braces for a multidimensional array. The standard requires that you can just run the values together in a flat list.
As long as you don't care about warnings: warning: missing braces around initializer (near initialization for 'min[0]')
10

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.

6 Comments

For existing libraries, there is Boost.MultiArray and Boost.uBlas (www.boost.org). The latter is more tailored to linear algebra. Think of Boost as an extension of the standard C++ library (or "The Stuff They Left Out of the Language and Standard Library(TM)").
@Emile: I didn't downvote, but new int[2][3][4] would do the trick. As for @Tronic's code, it just duplicates the effort of std::valarray.
std::vector is essentially a nice RAII wrapper for new[]/delete[] (and it also does a few other things) so I always prefer it over managing the memory manually. Granted, here it wastes a few bytes for keeping track of the container size, but on the other hand you can use that to calculate the 3D array dimensions. I don't see what std::valarray has to do with this, as I haven't defined any arithmetic operations for the array and valarray doesn't know how to appear as a multidimensional array.
@Potatoswatter: In my comment, I forgot to add "...with dimensions only known at runtime". Wait, that still doesn't make sense. I'll just shut up now. :-)
@Tronic: You get multidimensional access to a std::valarray by subscripting with a std::gslice. See the link at my answer. What do you mean, haven't defined any arithmetic operations for the array?
|
10

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;
        }
    }
}

1 Comment

int*** array; is useful when declaring a pointer to a not-yet-allocated 3D array in C.
3

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

https://cplusplus.com/reference/valarray/valarray/

No static initialization, but is that really essential?

1 Comment

Your comments/answer made me spawn a question on std::valarray: stackoverflow.com/questions/2187648/…
0

this is best method when you know the exact size of the array when you're writing the code. You use nested curly braces { } to define the values for each dimension.

The syntax is type arrayName[depth][height][width]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.