4

I have a problem with my code. I have some input for the class, the nmax und mmax. These are defined in header as

int nmax;
int mmax;

Then I have some arrays, defined in header as

double* Nline;
double** NMline;

and then I would like to allocate them in the main program. First, I assign to nmax und max a value from the input

nmax = nmax_in;
mmax = mmax_in;

and then I allocate the arrays

Nline = new double [nmax];
NMline = new double [nmax][mmax];

The problem is, the 1D array is this way allocated. But the 2D array not - the compiler writes: expression must have a constant value

Why the NLine was allocated and NMline not?

I understand but I don't know how to do it in my program and why for the 1D array this allocation is OK. Many thanks for your help

opalenzuela
  • 3,139
  • 21
  • 41
mumtei
  • 69
  • 1
  • 7

1 Answers1

7
double** NMline;

will declare pointer to array of pointers, it will not declare 2D array. You need to first allocate data for the array of pointers (pointers to rows):

NMline = new double*[nmax];

and then to initialize each row:

for(int i = 0; i < nmax; i++)
       NMline[i] = new double[mmax];

Don't forget to first delete all rows, and then the NMline itself:

for(int i = 0; i < nmax; i++)
       delete [] NMline[i];
delete [] NMline;
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91