ja*******@gmail.com wrote:
I'm having a ton of trouble initializing a multi-dimensional array
inside a constructor, largely because I don't know the size of the
array until runtime. I have a class that looks like this:
"Size" portion of array types in C++ must be a so called 'integral constant
expression' (ICE). The exact definition of ICE can be found in the language
specification, but the idea is that the size must be known at compile time.
Non-static class data members cannot be used in ICEs. This is what makes the
compiler to complain.
Since in your case array sizes are only known at run-time, there's no way to
achieve what you want with array type or type derived from array type (as the
'int (*)[size][size]' you are trying to use). There are different ways to solve
the problem:
1. Use a 1D array of size 'size * size * size' and simulate a 3D access by
manually transforming the 3D indices into the corresponding the 1D index:
[x][y][z] - [x * size * size + y * size + z]
(that's, BTW, how built-in arrays work in C/C++)
2. Use the well-known array-of-pointers idiom:
int*** arrayPtr = new int**[size];
// Then for each i
arrayPtr[i] = new int*[size];
// Then for each i, j
arrayPtr[i][j] = new int[size];
(the above is just an illustration of the idea; the actual implementation can be
done in a neater way).
3. (Might make the most sense out of three) Use
'std::vector<std::vector<std::vector<int >'.
class MyClass
{
public:
const int size;
MyClass( const int );
};
MyClass::MyClass( const int s )
: size( s )
{
int (*arrayPtr)[size][size] = new int[size][size][size];
}
When I compile this with g++ (actually, Apple's version of g++, in case
that matters), I get the following error:
myclass.cpp : In constructor 'MyClass::MyClass(int)':
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression
myclass.cpp.8: error: 'MyClass::size' cannot appear in a
constant-expression
--
Best regards,
Andrey Tarasevich