Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of 2D array with dynamic number of rows and fixed number of columns. C++

I'm having problem with creating my 2D dynamic array in C++. I want it to have dynamic number (e.g. numR) of "rows" and fixed (e.g. 2) number of "columns".

I tried doing it like this:

const numC = 2;
int numR;
numR = 10;
double *myArray[numC];
myArray = new double[numR];

Unfortunately, it doesn't work. Is it possible to do it in such a way?

Of course I could use double **myArray and initialize it as if both dimensions are dynamic (with numC used as limiter in loop) but I would like to avoid it if possible.

Thanks in advance.

like image 716
Moomin Avatar asked Dec 01 '25 20:12

Moomin


1 Answers

Is it possible to do it in such a way?

Yes:

double (*myArray)[numC] = new double[numR][numC];
// ...
delete[] myArray;

This may look a little unusual, but 5.3.4 §5 clearly states:

the type of new int[i][10] is int (*)[10]

Note that many programmers are not familiar with C declarator syntax and will not understand this code. Also, manual dynamic allocation is not exception safe. For these reaons, a vector of arrays is better:

#include <vector>
#include <array>

std::vector<std::array<double, numC> > vec(numR);
// ...
// no manual cleanup necessary

Replace std::array with std::tr1::array or boost::array, depending on your compiler.

like image 195
fredoverflow Avatar answered Dec 04 '25 11:12

fredoverflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!