[英]How to declare a dynamic 2D array in C++
I'm trying to define a dynamic 2D Array in C++ using the following definition:我正在尝试使用以下定义在 C++ 中定义一个动态二维数组:
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.我收到一个错误,新表达式中的数组大小必须是常量,不明白为什么,因为
Array
应该是动态的。
(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:对于分配有
new
的二维数组,您需要的是:
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
.另一种解决方案是使用
vector
。
int foo(string parameter){
const int n = parameter.length();
vector<vector<int>> Array(n, vector<int>(n));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.