关于C#:如何一次初始化多个struct变量?

How to initialize several struct variables at once?

对于像

这样的结构

1
2
3
4
5
struct data{
   int a;
   int b;
   int c;
};

如何一次用相同的值初始化该结构的多个实例?

代替:

1
struct data object1 = {0,0,0}, object2 = {0,0,0}, object3 = {0,0,0};


首先,我更喜欢 Linux 内核风格,并且更喜欢指定的初始化器。

我会做他们所做的,并创建一个宏来初始化你的结构。这使得添加元素和控制它们的初始化方式变得容易。

1
2
3
4
5
6
7
8
9
10
11
struct data {
   int a;
   int b;
   int c;
};

#define INIT_DATA { \\
    .a = 0, \\
    .b = 0, \\
    .c = 0, \\
}

并像这样使用它:

1
struct data mydata = INIT_DATA;

继续使用 Linux 风格,无论如何,一行中的这些变量不会超过一个。当添加/删除变量时,它可以更容易地查看不同的内容。有什么问题:

1
2
struct data old_data = INIT_DATA;
struct data new_data = INIT_DATA;

如果你有多个,它们应该是单个变量还是应该是一个数组?如果是这样,您可以利用 GNU 扩展来初始化范围:

1
2
3
struct data datas[N] = {
    [0 ... N-1] = INIT_DATA,
};

否则,您将需要使用常规的旧循环在运行时初始化数据。


您可以获取 struct 的数组并使用单个大括号括起来的初始值设定项,例如

1
 struct data object [3] = {0};

go 有多个该结构类型的变量,全部初始化为 0(或等效)。

这利用了初始化的特殊属性,引用 C11, chapter

The initialization shall occur in initializer list order, each initializer provided for a
particular subobject overriding any previously listed initializer for the same subobject;151)
all subobjects that are not initialized explicitly shall be initialized implicitly the same as
objects that have static storage duration.

以及具有 static 存储的对象的初始化,

[...] If an object that has static or thread storage duration is not initialized
explicitly, then:

a€" if it has pointer type, it is initialized to a null pointer;

a€" if it has arithmetic type, it is initialized to (positive or unsigned) zero;

a€" if it is an aggregate, every member is initialized (recursively) according to these rules,
and any padding is initialized to zero bits;

a€" if it is a union, the first named member is initialized (recursively) according to these
rules, and any padding is initialized to zero bits;

也就是说,如果您不希望将所有值初始化为 0,还有其他方法。正如 Jonathon Reinhart 先生在另一个答案中提到的那样,您可以使用指定的初始化程序。


how can I initialize several instances of that struct with identical values at once?

不是真的"一次",不管这意味着什么,但至少不重复自己(即遵循 DRY 原则)你可以这样做:

1
2
3
4
5
6
int main(void)
{
  struct data object1 = {1, 2, 3}, object2 = object1, object3 = object1;

  ...
}

或者每个定义单独一行:

1
2
3
4
5
6
7
8
int main(void)
{
  struct data object1 = {1, 2, 3};
  struct data object2 = object1;
  struct data object3 = object1;

  ...
}


创建一个结构数组并在循环中初始化它们。

1
2
3
4
5
6
7
8
struct data array[N_ITEMS];

for(i=0; i<N_ITEMS; i++)
{
    array[i].a=a;
    array[i].b=b;
    array[i].c=c;
}

如果要将所有字段初始化为0,可以使用memset:

1
 memset(array, 0, sizeof(array));