1

I'm trying to define a dynamic 2D Array in C++ using the following definition:

int foo(string parameter){
    const int n = parameter.length();
    int* Array = new int[n][n];
return 0;
}

I receive an error that array size in new expression must be constant, can't understand why because Array is supposed to be dynamic.

1
  • A dynamic 2D array in C++ is a std::vector<std::vector>. To fix your code you can int* Array = new int[n * n]; and access the elements with Array[row + n * col].
    – jabaa
    Commented Feb 1, 2022 at 15:49

1 Answer 1

1

(someone posted a shorter version of this in the comments while I was writing it).

What you need for a 2D array allocated with new is this:

int foo(string parameter){
    const int n = parameter.length();
    int* Array = new int[n*n];
    return 0;
}

And then access cells with appropriate indexing.

Another solution is to use vector.

int foo(string parameter){
    const int n = parameter.length();
    vector<vector<int>> Array(n, vector<int>(n));
    return 0;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.