c - 有没有更好的方法来改变结构中的每个变量,C

标签 c struct

我很好奇是否有更好的方法来更改结构中的每个变量而不是下面的代码块。

struct RuntimeData
{
    double runtime_ms, sum_ms, avg_time_ms, best_time_ms;
};

int main()
{
    struct RuntimeData selection;

    // The '0' values are just for example..
    selection.runtime_ms = 0;
    selection.sum_ms = 0;
    selection.avg_time_ms = 0;
    selection.best_time_ms = 0;
}

我宁愿能够做类似的事情......

struct RuntimeData selection;

selection = { .runtime_ms=0,
              .sum_ms = 0,
              .avg_time_ms = 0,
              .best_time_ms = 0
};

...或类似的东西。我知道你可以在初始化结构体时执行后面的代码块,但是在结构体已经初始化后会导致编译错误。

编辑:使用 Nate 和 Vlad 的答案,复合文字正是我所需要的!非常感谢。

最佳答案

您可以使用 compound literal :

struct RuntimeData selection;

void foo(void) {
  selection = (struct RuntimeData){ 0, 0, 0, 0 };
}

这可以与 designated initializers 结合使用:

struct RuntimeData selection;

void foo(void) {
  selection = (struct RuntimeData){ 
                    .sum_ms = 42.3,
                    .avg_time_ms = 123.4,
                    .best_time_ms = -7e17,
                    .runtime_ms = 0.0001 
  };
}

关于c - 有没有更好的方法来改变结构中的每个变量,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60234639/

相关文章:

c - 在C中通过地址传递struct-within-pointer-array-within-struct

c - 是否可以使结构数组的地址等于指向 malloc 内存的指针?

c - Structs 中的 Structs 按顺序排列

c - 如何在C中跟踪初始头指针?

C 和 libgcrypt。 Str 输入 gcry_error_t。然后加

c - IoCreateSymbolicLink 何时返回 STATUS_OBJECT_NAME_COLLISION

c - 我的结构设置是否正确,可以将城市(顶点)添加到无向加权图中以找到最短路径?

struct - 使用 envy 时如何用匹配结果填充结构体实例?

c++ - 使用 clang API 编译程序

c++ - 共享内存包含指针