使用->运算符

时间:2019-04-27 20:21:02

标签: c

我必须使用指向它的点来初始化一个结构,即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;


有什么方法可以使它更“紧凑”,而不是一一对应吗?我已经尝试过了,但是编译器的错误是相同的“'{'令牌之前的预期表达式”

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}};

1 个答案:

答案 0 :(得分:3)

是复合文字

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

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

您可以在这里进行实验:https://godbolt.org/z/yw_JC0