当我在两个不同的地方定义数组(具有相同的行)时,我找不到为什么下面的代码不能工作的原因。这是不是好的做法不是我的问题。我只想找到原因。
// Array Test: t.cpp
// If only the ONE LINE in question is enabled in either place
// it works/fails as indicated. I wonder why?
#include "iostream"
int a = 5; // Rows
int b = 4; // Columns
// int x[a][b]; // if done here: NoGo! WHY? <<<***************************
int main () {
int x[a][b]; // if done here: OK! <<<***************************
for (int r = 0; r < a; r++) {
for (int c = 0; c < b; c++) {
x[r][c] = (r*10+10) + (c+1);
std::cout << x[r][c] << " ";
}
std::cout << "\n";
}
std::cout << "\nARRAY CREATED \n\n";
}
如果全局定义数组,则需要在编译时知道数组的大小。您的变量A
和B
不是常量,因此在编译时不知道它们的值。
但是,如果您使用常量int a=5;const int b=4
,它可以按照您的预期工作。
注意,可变长度数组(即,非恒定大小说明符)是C99的一个特性,不是任何当前C++标准的一部分。