提问者:小点点

C++在main()之外定义数组的问题


当我在两个不同的地方定义数组(具有相同的行)时,我找不到为什么下面的代码不能工作的原因。这是不是好的做法不是我的问题。我只想找到原因。


// 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";
}


共1个答案

匿名用户

如果全局定义数组,则需要在编译时知道数组的大小。您的变量AB不是常量,因此在编译时不知道它们的值。

但是,如果您使用常量int a=5;const int b=4,它可以按照您的预期工作。

注意,可变长度数组(即,非恒定大小说明符)是C99的一个特性,不是任何当前C++标准的一部分。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|main|之外|定义|数组)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?