Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c - 如何根据C编程语言标准初始化结构(How to initialize a struct in accordance with C programming language standards)

I want to initialize a struct element, split in declaration and initialization.

(我想初始化一个struct元素,拆分为声明和初始化。)

This is what I have:

(这就是我所拥有的:)

typedef struct MY_TYPE {
  bool flag;
  short int value;
  double stuff;
} MY_TYPE;

void function(void) {
  MY_TYPE a;
  ...
  a = { true, 15, 0.123 }
}

Is this the way to declare and initialize a local variable of MY_TYPE in accordance with C programming language standards (C89, C90, C99, C11, etc.)?

(这是按照C编程语言标准(C89,C90,C99,C11等)声明和初始化MY_TYPE局部变量的MY_TYPE吗?)

Or is there anything better or at least working?

(还是有什么更好的方法,或者至少可以起作用?)

Update I ended up having a static initialization element where I set every subelement according to my needs.

(更新我最终得到了一个静态初始化元素,在其中根据需要设置了每个子元素。)

  ask by cringe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In (ANSI) C99, you can use a designated initializer to initialize a structure:

(在(ANSI)C99中,可以使用指定的初始化程序来初始化结构:)

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration."

(编辑:其他成员初始化为零:“省略的字段成员隐式初始化为与具有静态存储持续时间的对象相同。”)

( https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html )

(( https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html ))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...