Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - dynamic array in 1D works, the same in 2D doesn't work [duplicate]

Tags:

c++

arrays

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

like image 466
mumtei Avatar asked Mar 22 '23 09:03

mumtei


1 Answers

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;
like image 180
Nemanja Boric Avatar answered Apr 27 '23 10:04

Nemanja Boric