Reputation: 83
I would like to do this:
Class Obj{
private:
int a;
int b[a][3];
public:
Obj(int a);
}
So that i can specify the size of my array when creating my object.But I get this compilation error: error: array bound is not an integer constant
I don't want to use vectors, dos anyone know how I can do this? Thanks.
Upvotes: 1
Views: 73
Reputation: 55897
Array size should be constant
. There is only one way, without dynamic allocation - use predefined constant for all arrays of this class.
class Obj{
private:
static constexr int a = 5;
int b[a][3];
public:
Obj();
};
If you want different sizes, then you should allocate memory dynamically, if you don't use vectors.
Upvotes: 1
Reputation: 17928
If you want to depend on extension then ISO C99 allows variable length arrays through extension, have a look at it http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html, with this extension arrays are declared like any other automatic arrays, but with a length that is not a constant expression.
Side effect is your code will compile with compile which got this extension.
Upvotes: 0
Reputation: 527
You should use a dynamic allocation:
b = new int *[a] ;
//memory allocated for elements of each column.
for( int i = 0 ; i < a ; i++ )
b[i] = new int[3];
Upvotes: 0