简体   繁体   English

C Struct初始化:奇怪的方式

[英]C Struct initialization : strange way

While reading a code I came across, the following definition and initialization of a struct: 在阅读我遇到的代码时,结构的以下定义和初始化:

// header file
struct foo{
char* name;
int value;
};

//Implementation file
struct foo fooElmnt __foo;
// some code using fooElmnt
struct foo fooElmnt __foo = {
    .name = "NAME";
    .value = some_value;
}

What does this mean in C and how is it different from usual declarations? 这在C中意味着什么?它与通常的声明有什么不同?

It's called designated initialization , 它被称为指定初始化

In a structure initializer, specify the name of a field to initialize with .fieldname = before the element value. 在结构初始值设定项中,指定要在元素值之前使用.fieldname =初始化的字段的名称。 For example, given the following structure, 例如,给定以下结构,

  struct point { int x, y; }; 

the following initialization 以下初始化

  struct point p = { .y = yvalue, .x = xvalue }; 

is equivalent to 相当于

  struct point p = { xvalue, yvalue }; 

If you read on, it explains that .fieldname is called a designator . 如果你继续阅读,它解释了.fieldname被称为指示符

UPDATE: I'm no C99 expert, but I couldn't compile the code. 更新:我不是C99专家,但我无法编译代码。 Here's the changes I had to make: 这是我必须做出的改变:

// header file
struct foo{
char* name;
int value;
};

//Implementation file
//struct foo fooElmnt __foo;
// some code using fooElmnt
struct foo fooElmnt  = {
    .name = "NAME",
    .value = 123
};

Were you able to compile it? 你能编译吗? I used TCC . 我用过TCC

Those are designated initializers, introduced in c99. 这些是指定的初始化器,在c99中引入。 You can read more here 你可以在这里阅读更多

Without them, you'd use 没有他们,你会使用

struct foo fooElmnt __foo = {
    "NAME",
    some_value
};

While in this case it doesn't matter much - other than the c99 way is more verbose, and its easier to read which element is initialized to what. 虽然在这种情况下它并不重要 - 除了c99方式更冗长,并且更容易阅读哪个元素被初始化为什么。

It does help if your struct has a lot of members and you only need to initialize a few of them to something other than zero. 如果你的struct有很多成员并且你只需要将其中的一些初始化为零以外的东西,它确实有帮助。

This is a designated initialization. 这是一个指定的初始化。 This also initializing the fields by their name, which is more readable than anomynous initialization when the structures are getting large. 这也是通过名称初始化字段,这比结构变大时的异步初始化更具可读性。 This has been introduced by the C99 standard. 这是由C99标准引入的。

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

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