In C++, when I want to initialize an array of some length (of integers for instance) I can just write
int* tab;
tab = new int[size];
where size is given somewhere else. But how do I do that in the same manner, when it comes to a multidimensional array? I can't just add another dimension(s) in the second line, because compiler doesn't like that...
It's a simple question I guess. I need that, as I'm writing an assignment in object-oriented programming and 2D array is a private part of a class, which needs to be... constructed in the constructor (with 2 dimensions as parameters).
Using std::vector is the safe way:
std::vector<std::vector<int>> mat(size1, std::vector<int>(size2));
if really you want to use new yourself:
int** mat = new int*[size1];
for (std::size_t i = 0; i != size1; ++i) {
mat[i] = new int[size2];
}
And don't forget to clean resources:
for (std::size_t i = 0; i != size1; ++i) {
delete [] mat[i];
}
delete[] mat;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With