The problem is that in C++ array dimensions need to be known at compile, except possibly the first dimension, which you can supply to the array new[]
operator at runtime.
There are several ways to fix your code:
- Make
tab
a vector<vector<double> >
and let C++ standard library worry about managing the memory,
- Make
tab
a double**
, allocate new double*[size]
, and then allocate the individual rows in a loop, or
- Keep
tab
a double*
, allocate new double[size*size]
, and do your own index translation when accessing the values.
I think the first approach is best, because it lets you avoid potential leaks without writing too much code:
class foo
{
private:
// const int size; <<== You don't need it - tab.size() gives you the size
vector<vector<double>> tab;
public:
foo(int size);
};
foo::foo(int size)
: tab( vector<vector<double> >(size, vector<double>(size, 0.0) ) )
{
}
If you do decide to go with the second or the third approach, remember to follow The Rule of Three.