3

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).

4
  • 1
    Please see this: learncpp.com/cpp-tutorial/65-multidimensional-arrays Commented Dec 30, 2014 at 10:21
  • 3
    -1 use std::vector. Commented Dec 30, 2014 at 10:22
  • 1
    I've heard about vector, but I wanted to know if there's a way similiar to what can be done with one dimensional array... Commented Dec 30, 2014 at 10:27
  • 1
    "I've heard about vector". So you've heard about C++, now it's time to really learn it. Commented Dec 30, 2014 at 10:46

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

Comments

2

If you can afford std::vector instead of arrays you can use as syntax:

std::vector< std::vector<int> > matrix(rows, std::vector<int>(columns));

for (int i=0; i<rows; i++) {
    for (int j=0; j<columns; j++) {
        matrix[i][j] = i+j;
    }
}

Comments

0

If you get height/width parameters before the initialization of the array you can try:

int height = 10;
int width = 10;

//...

int tab[heigth][width];

2 Comments

you can not have run-time values as dimensions of automatic array.
That requires non standard extension: VLA.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.