C ++ - dynamic array in 1D works, the same thing in 2D does not work

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

int nmax; int mmax; 

Then I have some arrays defined in the header as

 double* Nline; double** NMline; 

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

 nmax = nmax_in; mmax = mmax_in; 

and then I allocate arrays

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

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

Why was NLine allocated and NMline not?

I understand, but I don’t know how to do this in my program, and why for a 1D array this distribution is fine. Thank you very much for your help.

+4
source share
1 answer
 double** NMline; 

declares a pointer to an array of pointers; it will not declare a 2D array. You must first select the data for an array of pointers (pointers to strings):

 NMline = new double*[nmax]; 

and then to initialize each line:

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

Remember to delete all lines first and then NMline :

 for(int i = 0; i < nmax; i++) delete [] NMline[i]; delete [] NMline; 
+7
source

Source: https://habr.com/ru/post/1502576/