为什么在尝试使用c ++创建二维数组时会出现此错误?

时间:2013-07-20 17:24:33

标签: c++ arrays parameters return-value max

首先欢迎并感谢您的帮助。我知道当你使用C ++创建一个数组时,索引必须是一个常量值,但我仍然得到同样的错误,让我复制并粘贴代码,以便你能理解我在说什么:

const int four = 4, five=5 , six = 6, seven = 7, eight = 8, nine = 9, ten = 10, eleven = 11, twelve = 12, thirteen = 13, fourteen = 14;

这是我的常数,对吗?现在看看这个:

switch(random_number)
{
case 4:   GenerarMatrix(four,four);         break;
case 5:   GenerarMatrix(five,five);         break;
case 6:   GenerarMatrix(six,six);           break;
case 7:   GenerarMatrix(seven,seven);       break;
case 8:   GenerarMatrix(eight,eight);       break;
case 9:   GenerarMatrix(nine,nine);         break;
case 10:  GenerarMatrix(ten,ten);           break;
case 11:  GenerarMatrix(eleven,eleven);     break;
case 12:  GenerarMatrix(twelve,twelve);     break;
case 13:  GenerarMatrix(thirteen,thirteen); break;
case 14:  GenerarMatrix(fourteen,fourteen); break;
}

我正在调用以下函数:

void GenerarMatrix( const int x, const int y)
{   
  int Matrix[x][y]; // Here I get an error, WHY if x and y are constant variables.

}

错误是表达式必须是常量值

2 个答案:

答案 0 :(得分:2)

数组维度必须是常量值并不完全正确。编译器必须知道在编译时的自动存储持续时间的数组的维度。

您正尝试使用允许在运行时期间更改尺寸的函数创建数组。您应该使用标准库中的容器来存储数据。

您的功能也可以像这样使用:

int i, j;
std::cin >> i; // Read value from standard input during program execution.
std::cin >> j;

GenerarMatrix(i, j);

这是不允许的。这就是编译器会给你一个错误的原因。

声明为const的变量与编译时可用的变量不同。声明const变量并使用运行时给定的值初始化它是完全可以的。例如:

int i;
std::cin >> i; // Value given at run time
const int j = i; // Ok to initialize constant variable with i.

您可以使用std::vector来定义您的功能:

void GenerarMatrix(const int x, const int y) {
    std::vector<std::vector<int>> Matrix(x, std::vector<int>(y, 0)); // Init to 0

    // ...
}

现在,您可以使用与数组相同的方式访问元素,例如Matrix[x][y],它将与运行时期间给出的维度一起使用。

另外:在即将推出的标准 C ++ 14 中引入了一个新容器std::dynarray,其中std::vector可以分配为在运行时给出的大小,但其大小将在构造时固定,并且在其生命周期内不会改变。如果您知道尺寸不会改变,这可能更适合您的需求。我不知道是否有任何编译器支持它。

答案 1 :(得分:0)

你真正想要的代码是什么? (我不明白,看起来也像编译器) 您可以使用以下命令为商店二维数组创建变量:

int[][] Matrix;

或者您可以使用以下内容初始化二维数组:

new int[x][y];

或以前的一行:

int[][] Matrix = new int[x][y];

int Matrix[x][y]

是不正确的声明(我认为)