C++表达式必须具有常数值

C++expression must have constant value

本文关键字:常数值 表达式 C++      更新时间:2023-10-16

我在dev c++中编写了这段代码,它很有效,但当我尝试在Visual Studio中运行它时,它会出现一个错误,比如表达式必须具有常数值

#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;
}

它在Visual Studio中不起作用的原因是因为它是一个可变长度的数组,而这些数组实际上不是C++的一部分。尽管如此,一些编译器还是能容忍它,但VS不会。

无论如何都无法获得正确结果的原因是rc没有在此处初始化:

int r, c, j;
int matrix[r][c];

这是未定义的行为。我的建议是使用嵌套的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));

我已经更新了我的代码,如下所示:

#include <iostream>
using namespace std;
int main() {
int r, c, j,i,k;
cout << "Enter the size of matrix: ";
cin >> j;
int matrix[j][j];
for (r = 0; r < j; r++) {
for (c = 0; c < j; c++) {
cout << "matrix" << "[" << r << "]" << "[" << c << "] = ";
cin >> matrix[r][c];
}
}
cout << "n";
for ( i = 0; i < j; i++) {
for ( k = 0; k < j; k++) {
cout << " "<<matrix[i][k] << " ";
}
cout << "n";
}
}

现在,它可以与Devc++配合使用。我是c++的初学者,理解std::vector有点困难。所以,这就是我这样做的原因。

编译时必须知道内置数组的大小,不能在运行时设置(或更改(它。

如果你是从教程中单独学习,而本教程教你使用内置数组,我建议你从书中学习,而不是像上面发布的那样。

简单地说:std::vector<int>就像一个整数数组,您可以在运行时更改它的大小。内置int matrix[5][5]的维度在运行时不能更改,必须在编写程序时决定,这是无效的。