[英]Double array with size as user input
我想做这样的事情
int n,m; //or cin>>n>>m;
a[n][m];
//then do whatever with the array
问题是Visual Studio给我错误,而dev c ++没有。 我想在VS中编译它。
即使你的编译器支持VLA(变长数组),你没有宣布a
正确:
int a[n][m];
^^^
您应该使用std::vector
这是一种标准方式
std::vector<std::vector<int> > a(n, std::vector<int>(m));
这取决于编译器...
对于此类需求,始终建议使用std::vector
。
但是,如果必须这样做 ,则可以像这样在堆上分配该内存...
使用new
(在C ++中推荐)...
cout << "Enter n & m:";
int n, m;
cin >> n >> m;
int** p = new int*[n];
for (int i = 0 ; i < n; i++) {
p[i] = new int[m];
}
或使用malloc
(在C中执行。不建议在C ++中使用)...
cin >> n >> m;
int** p = (int**) malloc (n * (int*));
for (int i = 0; i < n; i++) {
p[i] = (int*) malloc(m * (int));
}
用于int
的2D数组。
但是请记住在使用后将其delete
或free
。
您可以使用std::vector<Type>(n*m)
,这可能是最好的方法。
但是,如果您想继续使用该数组,我想如果您通过调用new / malloc在堆上而不是堆栈上分配内存,它将可以编译。 但是请提醒自己,释放内存之后,请在操作之前检查用户输入,以防止恶意输入。
数组需要常量paras。
可以使用vector< vector <int> >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.