gpt4 book ai didi

c - 在文件作用域中使用C初始化数组大小

转载 作者:行者123 更新时间:2023-12-02 06:28:29 24 4
gpt4 key购买 nike

我想基于计算初始化一个数组,但是当我尝试这样做时,编译器给我一个错误(我使用的是GCC版本6.3.0):

const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
char textgrid[SCREEN_HEIGHT/16][SCREEN_WIDTH/16];

编译器错误如下:
error: variably modified 'textgrid' at file scope

有没有办法在文件范围内执行此操作?

看来我无法使用计算作为#define语句的一部分来完成此操作,因为以下内容给了我相同的错误:
#define TEXTGRID_WIDTH (SCREEN_WIDTH / 16)
#define TEXTGRID_HEIGHT (SCREEN_HEIGHT / 16)
char textgrid[TEXTGRID_HEIGHT][TEXTGRID_WIDTH];

最佳答案

根据C标准(6.7.6.2数组声明符)

  1. ... If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.


和(6.7.6.2数组声明符)

2 If an identifier is declared as having a variably modified type, it shall be an ordinary identifier (as defined in 6.2.3), have no linkage, and have either block scope or function prototype scope. If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.



最后(6.6常量表达式)

6 An integer constant expression117) shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof operator.



因此,您可以使用已定义的命名常量,例如
#define SCREEN_WIDTH  800
#define SCREEN_HEIGHT 600

或列举者
enum { SCREEN_WIDTH = 800, SCREEN_HEIGHT = 600 };

关于c - 在文件作用域中使用C初始化数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48130858/

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