c - 为什么不能将静态结构指针初始化为变量的地址

标签 c pointers static

当我以下面的形式初始化结构时出现错误

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 保持为静态,以便它的范围保留在同一个文件中。 请在此帮忙

最佳答案

这是因为 astatic 类型,它应该使用 常量 或变量值进行初始化(在您的情况下是 &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/

相关文章:

c中符号转换为小写字母

c - 是否有充分的理由不在一个节点中包含多个节点指针以在多个数据结构中使用?

pointers - 通过将指针传递给 Go 中的函数来获取不同的值

c - 用 8 位整数替换部分 16 位整数

variables - NextJS 静态导出指定 .env

java - Java 中的私有(private)辅助方法与公共(public)静态实用程序方法

c - 了解简单 C 程序的汇编

c - 在 C 中处理字符数组

c - 使用accept接收顺序数据

php - 将一个静态变量分配给另一个静态变量。为什么会抛出错误?