Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example, given a structure S:

typedef struct {
  int a, b;
} S;

... and a method which takes a pointer to S, can I assign it the value of an aggregate initializer1 all in one line? Here's my existing solution which uses a temporary:

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

I'm using C11.


1 For the very rare super-pedant who doesn't understand my question because somehow "aggregate initializer" wouldn't apply here because the LHS is not declaring a new object, I mean "aggregate-initializer-like syntax with the braces and stuff".

like image 263
BeeOnRope Avatar asked Dec 09 '25 13:12

BeeOnRope


1 Answers

Yes, you can using the compound literals 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;
}

Demo

like image 164
Eugene Sh. Avatar answered Dec 11 '25 01:12

Eugene Sh.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!