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.
CodePudding user response:
(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;
}