简体   繁体   English

用->运算符初始化结构指针

[英]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) 我必须使用指向它的点来初始化结构,以这种方式,upper_left是点(10,25)和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 您可以在这里进行实验: https//godbolt.org/z/yw_JC0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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