[英]Can someone explain me this C structure syntax?
I found on this official gnu gcc website that they initialize structures like that:我在这个官方 gnu gcc 网站上发现他们初始化了这样的结构:
struct f1 {
int x; int y[];
} f1 = { 1, { 2, 3, 4 } };
struct f2 {
struct f1 f1; int data[3];
} f2 = { { 1 }, { 2, 3, 4 } };
At first I thought it was a default initialization for the struct, but I tested it and it doesn't auto-initialize the struct when declared, so what's the point of using this (I compiled my program with gcc of course).起初我认为这是结构的默认初始化,但我对其进行了测试,并且在声明时它不会自动初始化结构,所以使用它有什么意义(我当然用 gcc 编译了我的程序)。
The code I tried:我试过的代码:
#include <stdio.h>
struct a{
int x;
int y;
} a = {42, 42};
int main(void)
{
struct a foo;
printf("%d\n%d\n", foo.x, foo.y);
return (0);
}
And it outputs random uninitialized data instead of它输出随机未初始化的数据而不是
42
42
Your confusion seems to stem from the fact that you do not understand the syntax.您的困惑似乎源于您不了解语法这一事实。
struct f1 {
int x; int y[];
} f1 = { 1, { 2, 3, 4 } };
defines a variable named f1
with it's members initialized.定义了一个名为
f1
的变量,并初始化了它的成员。
In your example, you also have a variable a
initialized in the global scope, but you also have the same variable a
in main
scope, which is left uninitialized.在您的示例中,您还在全局 scope 中初始化了一个变量
a
,但在main
scope 中也有相同的变量a
,该变量未初始化。
I misunderstood, this is equivalent to struct f1 f1 = { 1, {2, 3, 4}};
我误解了,这相当于
struct f1 f1 = { 1, {2, 3, 4}};
, the fact that they used the same name f1
made me think that this was a new syntax. ,他们使用同名
f1
的事实让我觉得这是一种新语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.