hi,
I am trying to declare a 2D array in a member function in C++ , where its size changes everytime i run the program.

but it is giving error like " a constant expression is required "
but i cannot make the size constant, as i need to change the size everytime i run the program.

plz help.

code is as follows :

int rowval = x->getrow();
int colval = x->getcol();
rowval+=1;
colval+=1;
float axisval [ rowval ] [colval] ; // error point

but it is giving error like " a constant expression is required "

Current C++ standard requires that an array declaration as you're trying must use constant values for the dimension sizes. Either literal values int array[10][20] or some other type of contant (non-changeable) value, like

const int ROWS = 10;
const int COLS = 20;

int arr[ROWS][COLS];

To create the array with sizes provided at runtime, you'll have to use dynamic memory allocation. You need to create a pointer to pointer, then allocate rows' worth of pointers, then initialize them to column size dynamic arrays.

Do a little research on that, and let us know what you find.

A quick point to note is that g++(and other compiler that support c99) allow VLA(Variable Length Arrays), if which you can specify a variable as the length of the array. i.e. the following statement are valid

int a,b;
cin>>a>>b;
int arr[a][b];

But then, the C99 standards are not implemented by some compiler's like few from Microsoft. So rather do not use them as the code will not be portable.
Regarding your problem, use vectors of vectors instead of a 2-dim array.
But if you insist on arrays, be ready to scratch your head a bit, as multi-dim dynamic array can be a back pain.

Yes, some compilers have adopted the C99 array methods. I didn't mention that because, obviously, the OP's compiler does not support that.

But if you insist on arrays, be ready to scratch your head a bit, as multi-dim dynamic array can be a back pain.

I'd say the pain is actually a little lower. :D

Use vectors!

#include <vector>

int a,b;
cin>>a>>b;
vector<int> InnerVector(a, 0);

vector<vector<int> > OuterVector(b, InnerVector);

I'd say the pain is actually a little lower. :D

Lower? hmm, may be, it is personal taste or something. I mean handling pointer's to pointers, and freeing them from memory, off course is a bonus effort.
Anyway....... but the vectors rock!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.