簡體   English   中英

C++ 問題定義 main() 之外的數組

[英]C++ question defining an array outside of 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";
}

如果全局定義數組,則需要在編譯時知道其大小。 在 function 中,數組將在堆棧上創建,因此其大小可能是可變的(但請參閱下面的備注)。 您的變量ab不是常量,因此它們的值在編譯時是未知的。

通過將它們聲明為常量,它可以按您的預期工作:

const int a = 5; // Rows
const int b = 4; // Columns

int x[a][b];

備注:可變長度 arrays(即非常量大小說明符)是 C99 功能,不屬於任何當前 C++ 標准。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM