1

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.

5
  • If you're not using vectors, welcome to the painful world of dynamic memory allocation. Commented Apr 4, 2013 at 9:49
  • As @chris says .. you need to do it your self with the new operator or malloc. Commented Apr 4, 2013 at 9:50
  • It's even worse in a class because you have to fill in three or five new members. Commented Apr 4, 2013 at 9:51
  • Have to mention it: blogs.msdn.com/b/oldnewthing/archive/2013/02/06/10391383.aspx Commented Apr 4, 2013 at 9:56
  • Well the reason I dont wan't to use vectors is that I don't now how to deal with vectors of array. In this i would like an array of 'a' arrays of size 3... Commented Apr 4, 2013 at 10:10

3 Answers 3

1

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.

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

1 Comment

What's the point of indicating 'a' in ;y constructor if it's constant ?
0

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

1 Comment

Might as well keep it at int (*b)[3].
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.