gpt4 book ai didi

c++ - 如何用全局变量声明全局数组的长度?

转载 作者:搜寻专家 更新时间:2023-10-31 01:01:17 25 4
gpt4 key购买 nike

我想用全局变量声明数组的长度。但是我遇到了错误,我对解决这个问题感到困惑。

int BARIS = 8;
//I get error when declare Squares Array with global variable (BARIS variable)
int SquaresInfo[BARIS];

int main(int argc, const char * argv[]) {
cout << "\n\n\n\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Tekan ENTER untuk masuk ke permainan";
if(cin.get() == '\n' ) {
system("clear");
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
gameInterface();
} else {
cout << " ";
}

return 0;
}

enter image description here

声明 SquareInfo 数组的长度时出现错误。我很困惑如何用全局变量声明数组长度

最佳答案

数组的大小应为常量表达式(大于 0)。更改此声明

int BARIS = 8;

const int BARIS = 8;

C++ 标准不允许可变长度数组 (VLA),尽管一些编译器有自己的语言扩展,允许使用 VLA。此外,VLA(s) 应具有自动存储期限。也就是说,如果您被允许定义一个 VLA,那么它应该是一个本地数组

来自允许使用 VLA 的 C 标准(6.7.6.2 数组声明符)

  1. ...If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.

如果变量可能不是常量,则使用 std::vector<int>而不是数组。例如

#include <vector>

//...

int BARIS = 8;
std::vector<int> SquaresInfo( BARIS );

关于c++ - 如何用全局变量声明全局数组的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com