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

标签 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.

}

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

最佳答案

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

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

你的函数也可以这样使用:

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 可以分配一个在运行时给定的大小,但它的大小将在构造时固定,并且在其生命周期内不会改变。如果您知道尺寸不会改变,这可能更适合您的需要。不过,我不知道是否有任何编译器支持它。

关于c++ - 为什么在尝试使用 C++ 创建二维数组时出现此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764736/

相关文章:

Java 数组操作

Java : logging execution history as XML

c++ - 如何以编程方式更改进程的执行路径?

c++ - 在捕获鼠标但窗口未聚焦时捕获键盘事件 (Win32)

c# - 快速修复错误 : System. AccessViolationException

c - 动态字符串输入并在 C 中对它们进行排序

c++ - 包括来自不同目录的头文件?

mysql - 内爆数组 -> 检查字符 -> 插入数据库

asp.net - Oracle中Link DB参数问题

c++ - 函数的参数顺序