Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment vs. Initialization: Initializing structs inside another struct in C

Tags:

c

struct

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?

like image 654
Galaxy Avatar asked Mar 11 '26 16:03

Galaxy


1 Answers

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};
like image 131
Some programmer dude Avatar answered Mar 13 '26 14:03

Some programmer dude