Given a pointer to a structure, can I assign the result of an aggregate initializer to a structure in one line?
For example, given the structure of S:
typedef struct {
int a, b;
} S;
... and the method that takes a pointer to S
, can I assign it the value of the aggregate initializer 1 all on one line? Here's my existing solution that uses a temporary:
void init_s(S* s) {
S temp = { 1, 2 };
*s = temp;
}
I am using C11.
1 For a very rare superpedant who doesn't understand my question because some kind of "aggregate initializer" is not applicable here, because LHS does not declare a new object, I mean "aggregate syntax like syntax with curly braces, etc. ".
+3
source to share
1 answer
Yes, you can use the compound literal syntax :
#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;
}
+5
source to share