Gam*_*afa 2 c++ arrays dev-c++ multidimensional-array visual-studio
我已经用dev c ++编写了此代码,并且可以工作,但是当我尝试在Visual Studio中运行它时,会出现错误,例如expression必须具有恒定值。
#include <iostream>
using namespace std;
int main() {
int r, c, j;
int matrix[r][c];
cout << "Enter the size of matrix: ";
cin >> j;
for (r = 0; r < j; r++) {
for (c = 0; c < j; c++) {
cout << "matrix" << "[" << r << "]" << "[" << c << "] = ";
cin >> matrix[r][c];
}
}
cout << "\n";
for (int i = 0; i < j; i++) {
for (int k = 0; k < j; k++) {
cout << " "<<matrix[i][k] << " ";
}
cout << "\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它不能在Visual Studio中工作的原因是因为它是一个可变长度数组,而实际上并不是C ++的一部分。某些编译器仍然可以容忍它,但是VS不能。
无论如何,您都无法获得正确的结果的原因是,r并且c未在此处初始化:
int r, c, j;
int matrix[r][c];
Run Code Online (Sandbox Code Playgroud)
那是未定义的行为。我的建议是使用嵌套的std::vector(并在阅读大小后进行嵌套):
#include <vector>
...
int r, c, j;
cout << "Enter the size of matrix: ";
cin >> j;
std::vector<std::vector<int>> matrix(j, std::vector<int>(j));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |