简体   繁体   中英

Initializing an structure pointer with -> operator

I have to initialize an structure using a point to it, in a way that upper_left is the point (10,25) and lower_right(20,15)

struct point {int x, y;};
struct rectangle {struct point upper_left, lower_right;};

struct rectangle *p;

p = malloc(sizeof(*p));

p->upper_left.x = 10;
p->upper_left.y = 25;
p->lower_right.x = 20;
p->lower_right.y = 15;


Is there any way to do it more "compact" and not one by one? I've tried this but the errors from the compiler are the same "Expected expression before '{' token"

p->upper_left = {10, 25};
p->lower_right = {20,15};

/////////////
p->upper_left = {.x = 10, .y = 25};
p->lower_right = {.x = 20, .y = 15};

//////////////////////////////

*p = {.upper_left = {10, 25}, .lower_right = {20, 15}};

Yes compound literal

  p->upper_left = (struct point){10, 25};

  *p = (struct rectangle){.upper_left = {10, 25}, .lower_right = {20, 15}};

you can experiment yourself here: https://godbolt.org/z/yw_JC0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM