Home > Enterprise >  How do I initialize a struct inside struct with members variables?
How do I initialize a struct inside struct with members variables?

Time:02-26

I defined a struct called Object and, inside this struct there are 3 more structs.

The collision_box should be tied together with position and size. Whenever I update the position and size, the collision_box should get the same values.

Before that I was just copying the position and size values to collision_box in the Init and Update function. It was working fine, but I think this should also work with pointers so I don't have to copy the values every time.

// Object definition 
typedef struct Object{
    Vector2 position; // typedef struct float x,y
    Vector2 size;     // typedef struct float x,y

    // When ever I update position and size the collision_box should get the same values
    // without copying them in the Update function.
    Rectangle collision_box = {position.x, position.y, size.x, size.y}; // typedef struct float x,y,width,height

}Object;

// Extension of Object
typedef struct Player{
    Object* o;
}Player;

// Update Players position and size
void UpdatePlayer(Player* player)
{
    player->o->position = (Vector2){100.0f, 100.0f};
    player->o->size = (Vector2){20.0f, 20.0f};
}

// player.o->collision_box should always be tied to player.o->position and player.o->size
printf("%f/n", player.o->collision_box.x);  
printf("%f/n", player.o->collision_box.y);
printf("%f/n", player.o->collision_box.width);  
printf("%f/n", player.o->collision_box.height);

Output

100.0
100.0
20.0
20.0

CodePudding user response:

You could declare your Object as a union, rather than as a struct, with the position and size members themselves being enclosed in an inner, anonymous structure.

That way, the two Vector2 types will occupy the same memory as the Rectangle member, and any changes to the former will also be made to the latter (and vice versa):

typedef union tagObject {
    struct {
        Vector2 position, size;
    };
    Rectangle collision_box;
}Object;

This gives you the ability to refer to the data either through the position and size members, or through the collision_box member.

Test code (correcting your /n to \n and adding some local variables to the main function so that it works):

int main()
{
    Player player;
    Object object;
    player.o = &object;
    UpdatePlayer(&player);
    // player.o->collision_box should always be tied to player.o->position and player.o->size
    printf("%f\n", player.o->collision_box.x);
    printf("%f\n", player.o->collision_box.y);
    printf("%f\n", player.o->collision_box.width);
    printf("%f\n", player.o->collision_box.height);
}

Output:

100.000000
100.000000
20.000000
20.000000
  • Related