I have a struct with two fields which are structs themselves. I want to use an initializer list to assign the fields of the internal structs, without having to assign each single field manually.
struct point
{
int x;
int y;
};
struct rectangle
{
struct point p1;
struct point p2;
};
struct rectangle r2;
r2.p1 = {5, 6};
r2.p2 = {7, 20};
However this code won't compile:
structs3.c:105:11: error: expected expression before ‘{’ token
r2.p1 = {5, 6};
^
structs3.c:106:11: error: expected expression before ‘{’ token
r2.p2 = {7, 20};
^
Why doesn't this work? What is the reason?
You could do it when defining r2, like
struct rectangle r2 = {
{5, 6},
{7, 20}
};
Or using compound literals as in
r2.p1 = (struct point){5, 6};
r2.p2 = (struct point){7, 20};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With