如何使用成员变量初始化结构内部的结构?

How do I initialize a struct inside struct with members variables?

我定义了一个名为 Object 的结构,在这个结构中还有 3 个结构。

collision_box 应与 positionsize 并列。每当我更新位置和大小时,collision_box 应该得到相同的值。

在此之前,我只是在 Init 和 Update 函数中将位置和大小值复制到 collision_box。它运行良好,但我认为这也适用于指针,因此我不必每次都复制值。

// 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);

输出

100.0
100.0
20.0
20.0

您可以声明 Object as a union,而不是 structpositionsize 成员本身被包含在一个内部, 匿名结构。

这样,两个 Vector2 类型将占用与 Rectangle 成员相同的内存,并且对前者的任何更改也会对后者进行(并且 反之亦然):

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

这使您能够通过 positionsize 成员,或通过 collision_box 成员引用数据。

测试代码(将您的 /n 更正为 \n 并向 main 函数添加一些局部变量以使其工作):

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

输出:

100.000000
100.000000
20.000000
20.000000