简体   繁体   English

C中的静态数组初始化

[英]Static array initialization in C

I am reading the book Let us C by Yashavant Kanetkar. 我正在阅读Yashavant Kanetkar的书“ 让我们来自C”

In the Array of Pointers section there is a section of code which is giving me problems: 在指针数组部分,有一段代码给我带来了问题:

int main()
{
    static int a[]={0,1,2,3,4}; //-----------(MY PROBLEM)
    int *p[]={a,a+1,a+2,a+3,a+4};
    printf("%u %u %d\n",p,*p,*(*p));
    return 0;
}

What I don't understand is why has the array a have to be initialized as static. 我不明白为什么数组a必须初始化为静态。 I tried initializing it without the static keyword but I got an error saying "illegal". 我尝试在没有static关键字的情况下初始化它,但是我收到了一条错误,说“非法”。 Please help. 请帮忙。

C90 (6.5.7) had C90(6.5.7)有

All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions. 具有静态存储持续时间的对象的初始值设定项中的所有表达式或具有聚合或联合类型的对象的初始化列表中的所有表达式都应为常量表达式。

And you are initializing an object that has an aggregate type, so the value must be known at compile time and the address of automatic variables are not in that case. 并且您正在初始化具有聚合类型的对象,因此必须在编译时知道该值,并且在这种情况下不会自动变量的地址。

Note this has changed in C99 (6.7.8/4) 请注意,这已在C99(6.7.8 / 4)中发生变化

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals. 具有静态存储持续时间的对象的初始化程序中的所有表达式应为常量表达式或字符串文字。

The constraint on object with aggregate or union type has been removed and I've not found it placed somewhere else. 对具有聚合或联合类型的对象的约束已被删除,我没有发现它放在其他地方。 Your code with static removed should be accepted by a C99 compiler (it is by gcc -std=c99 for instance, which seems to confirm that I've not overlooked a constraint elsewhere). 你的静态删除代码应该被C99编译器接受(例如,它是由gcc -std=c99 ,这似乎证实我没有忽略其他地方的约束)。

My guess would be that the contents of an array initialiser have to be a compile-time constant. 我的猜测是数组初始化程序的内容必须是编译时常量。 By using static on a local variable in a function you essentially make that variable global, except with a local scope. 通过在函数中的局部变量上使用static ,除了使用局部范围外,您基本上将该变量设为全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM