gpt4 book ai didi

c - GCC/clang 编译错误,函数作用域静态指针指向未命名数组

转载 作者:行者123 更新时间:2023-12-05 03:16:27 28 4
gpt4 key购买 nike

为什么 GCC 和 clang 在定义函数作用域的 static 指针时分别显示“错误:初始化元素不是常量”和“错误:初始化元素不是编译时常量”初始化为一个未命名的数组;但是,当在文件范围内定义指向相同未命名数组的相同静态指针时,它们管理得很好。

我使用嵌入式 H/W 编译器编译了相同的程序,编译没有错误。

这是一个错误激活的代码片段:

int foo()
{
static int *ptr = (int[]) { 9, 8, 7 }; /* COMPILE ERROR */
return ptr[2];
}

int main(void)
{
return foo();
}

这里是一个类似的代码片段,在文件范围内带有 static 指针,GCC 和 clang 编译没有问题:

static int *ptr = (int[]) { 9, 8, 7 }; /* File-scope is fine */

int foo()
{
return ptr[2];
}

int main(void)
{
return foo();
}

我当然可以在我的函数中定义一个单独的静态数组并将我的静态指针指向该数组,但我想使用一个未命名的数组。我尝试了不同的编译器标志但无济于事:

  • -std=c90
  • -std=c99
  • -std=c11
  • -std=gnu11

最佳答案

问题在于复合文字的范围(即您的“未命名数组”);当它用于文件范围时(如在您的第二个代码段中),C 标准指定它具有静态 存储持续时间,因此它可以用作初始值设定项。

但是,在 block 作用域 声明的复合文字(如您的第一个示例)具有自动 存储持续时间,因此它的地址不能用作此上下文中的初始值设定项.

来自 this Draft C11 Standard :

6.5.2.5 Compound literals


5     The value of the compound literal is that of an unnamed objectinitialized by the initializer list. If the compound literal occursoutside the body of a function, the object has static storageduration; otherwise, it has automatic storage duration associated withthe enclosing block.

关于c - GCC/clang 编译错误,函数作用域静态指针指向未命名数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74639056/

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