当我以下面的形式初始化结构时出现错误
static struct A* a = &apple->queue[queue_number];
static struct B* b = &banana->queue_a[queue_number];
我收到错误
Error: #28: expression must have a constant value
我想将指针 a 和 b 保持为静态,以便它的范围保留在同一个文件中。 请在此帮忙
最佳答案
这是因为 a
是 static
类型,它应该使用 常量
或变量值进行初始化(在您的情况下是 &apple->queue[queue_number]
)在编译时已知,而不是在运行时已知。
来自C标准
All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.
我想将指针 a 和 b 保持为静态?一种方法是使用 NULL
初始化第一个 a
并对其进行测试。
static struct A *a = NULL;
if(a == NULL) { /* point to remember when a become NULL it initialize again a */
a = &apple->queue[queue_number]; /*initialize expected value here */
}
也许你想读这个Error "initializer element is not constant" when trying to initialize variable with const
关于c - 为什么不能将静态结构指针初始化为变量的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50187892/