【问题标题】:I can't have variable as size when I'm declaring the array? [duplicate]声明数组时不能将变量作为大小? [复制]
【发布时间】:2019-06-16 13:12:54
【问题描述】:

所以我有一个二维数组,称为 char Screen[50][5]; 当我这样声明时 -> char Screen[50][5];一切正常。 但是,当我将变量放在方括号中而不是数字中时,我会收到错误消息说屏幕未声明。

我试过这种声明 char[][] Screen = new char[ScreenWidth][ScreenHeight]; 的方法太

int ScreenWidth = 50;
int ScreenHeight = 5;
char Screen[ScreenWidth][ScreenHeight];

[错误] 'Screen' 未在此范围内声明

【问题讨论】:

标签: c++


【解决方案1】:

该错误与您使用数组大小​​的变量无关,但是,这是不可能的,C-Style 数组大小必须在编译时知道。

您的错误是您在其他地方使用 Screen,但是这一行错误,因此 Screen 永远不会被定义。

对变量使用constexpr 关键字,这是可能的

constexpr int ScreenWidth = 50;
constexpr int ScreenHeight = 5;
char Screen[ScreenWidth][ScreenHeight];

编辑: 您也许可以将其标记为 const 而不是 constexpr,编译器很可能会对其进行优化,但您不能依赖它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2011-02-21
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多