C:用常量子结构初始化结构

C: Initialize struct with constant sub-struct

我有一个名为 single_instance 的结构实例化。此实例包含 struct example_type.

类型的常量对象
typedef struct {
  int n;
} example_type;

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance;

假设我想将 single_instance.t1 初始化为 {1} 并将 single_instance.t2 初始化为 {2}

最优雅的方法是什么?

无法进行内联初始化:

struct {
  int some_variables;
  // ...
  const example_type t1 = {1};
  const example_type t2 = {2};
  // ...
} single_instance;

这也行不通:

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance {0, {0}, {1}};

我已经阅读了与该主题相关的多个其他线程,但它们似乎都引用了使用 "a name" 初始化结构。在这种情况下,我只想要 single_instance 的一个实例化,因此该类型不应该有名称。

这对我有用(也许你只是在初始化中缺少 =):

#include<stdio.h>

typedef struct {
  int n;
} example_type;

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance = {0, {1}, {2}};

int main() {

    printf("%d %d %d\n", single_instance.some_variables, single_instance.t1.n, single_instance.t2.n);
}

您可以使用指定初始化器显式初始化您感兴趣的成员。然后其余成员将被隐式初始化为0。

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance = {.t1 = {1}, .t2 = {2}};