gpt4 book ai didi

无法使用我认为应该是编译时常量的内容来初始化静态数组

转载 作者:行者123 更新时间:2023-12-04 09:33:42 25 4
gpt4 key购买 nike

我正在尝试根据我认为应该是编译时常量的大小来初始化静态数组。

这很容易修复,但只是不使用静态,但我根本没想到这个问题会出现。这可能会在将来给我带来其他问题。

相关部分:

typedef struct {
GPIO_TypeDef* Port;
uint16_t Pin;
} PortPin;

typedef struct {
I2C_HandleTypeDef *Handle;
uint16_t Address;
PortPin Interrupt;
PortPin Shutdown;
} VL53L1_Dev_t;

//This one is bigger but I've kept it short to keep it readable. It's 3 elements in my code
static VL53L1_Dev_t Sensors[] = {
{//1
&hi2c2,
0x52,
{
GPIOA,
GPIO_PIN_11
},
{
GPIOA,
GPIO_PIN_10
}
}
}
static const int sensorCount = sizeof(Sensors)/sizeof(Sensors[0]);
static uint8_t encodedData[sensorCount * 2];//Compiler doesn't like this part

由于 Sensors 是在编译时完全定义的,因此我预计sensorCount 也是一个编译时常量。显然不是,因为我无法使用它来声明和初始化静态数组。我不明白为什么。

最佳答案

在文件范围内声明的数组的大小必须是整数常量表达式。它在 C standard 的第 6.6p6 节中定义。 :

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, 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 or _Alignof operator .

因此,即使声明为 const,变量的内容也不是此类表达式的一部分。

如果您将 sensorCount 定义为宏,则表达式 sizeof(Sensors)/sizeof(Sensors[0]) 是一个编译时间常数。

#define SENSOR_COUNT  (sizeof(Sensors)/sizeof(Sensors[0]))
static uint8_t encodedData[SENSOR_COUNT * 2];

关于无法使用我认为应该是编译时常量的内容来初始化静态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54581237/

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