给定一个指向结构的指针,我可以在一行中将聚合初始化器的结果分配给结构吗?

Given a pointer to a structure, can I assign the structure the result of an aggregate-initializer in one line?

例如,给定结构 S:

typedef struct {
  int a, b;
} S;

... 和一个采用指向 S 的指针的方法,我可以在一行中为其分配聚合初始值设定项 1 的值吗?这是我现有的使用临时解决方案的解决方案:

void init_s(S* s) {
  S temp = { 1, 2 };
  *s = temp;
}

我正在使用 C11。


1 对于不理解我的问题的非常罕见的超级学究,因为不知何故 "aggregate initializer" 在这里不适用,因为 LHS 没有宣布新的对象,我的意思是 "aggregate-initializer-like syntax with the braces and stuff".

是的,您可以使用 compound literals 语法:

#include <stdio.h>

typedef struct {
  int a, b;
} S;

int main(void) {
    S s;
    S *p = &s;

    *p = (S){1,2};

    printf("%d %d\n", p->a, p->b);
    return 0;
}

Demo