0

In the following c++ programm:

class matrix {
public:
  int n;
  double **x;

  matrix(int n) : n(n) { 
    x=new double[n][n]; 
    for (int i=0;i<n;i++)
    { 
       for(int j=0;j<n;j++)
       {
         x[i][j]=0;
       }
    }
 }
 ...

I get the following error: "'n' cannot appear in a constant-expression". Since im relatively new to cpp i dont really know why this error occurs (especially because i did almost the exact same thing with a class called vector and there it was no problem at all) and how to fix it. I would really appreciate any help.

Hylta
  • 3
  • 1
  • 1
  • 3

1 Answers1

2

In this expression

x=new double[n][n];

all dimensions except the leftmost shall be constant expressions.

The correct approach is

x = new double *[n];
for ( int i = 0; i < n; i++ ) x[i] = new double[n];

for (int i=0;i<n;i++)
{ 
   for(int j=0;j<n;j++)
   {
     x[i][j]=0;
   }
}

Or if your compiler supports C++ 2011 then it can be done simpler without explicit initialization in the loops

x = new double *[n];
for ( int i = 0; i < n; i++ ) x[i] = new double[n] {};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Also don't forget to release the memory – P0W Dec 01 '13 at 14:52
  • In C++11 : `auto arr = new double[n][n]();` – P0W Dec 01 '13 at 14:53
  • For a *matrix*, you should probably *not* use an array of pointers, but a contiguous section of memory. – dyp Dec 01 '13 at 14:53
  • @P0W You are wrong. auto arr = new double[n][n](); is not valid in C++11 because the rightmost expression must be a constant expression. – Vlad from Moscow Dec 01 '13 at 15:08
  • @VladfromMoscow Did I said something, that it should, I just wrote that it can be done using that statement, of course it must be a `const` Intention was to show `()` usage for initialization without for loop – P0W Dec 01 '13 at 15:12