I'm a little confused about the best way to initialize complex structs (struct of struct)
I basically have a setup like this
typedef struct {
float x;
float y;
} Vectorf;
typedef struct {
Vectorf position;
Vectorf direction;
Vectorf velocity;
} Player;
What would be the best way to initialize a Player object?
Variant A
Vectorf position = {1.0f, 1.0f};
Vectorf direction = {1.0f, 0.0f};
Vectorf velocity = {0.0f, 0.0f};
Player player = {position, direction, velocity};
Variant B
Player *player = malloc(sizeof(Player));
player->position.x = 1.0f;
player->position.y = 1.0f;
player->direction.x = 1.0f;
player->direction.y = 0.0f;
player->velocity.x = 0.0f;
player->velocity.y = 0.0f;
--- Stuff ---
free(player);
Or even create a function like
Player *createPlayer(float px, float py...)
Player createPlayer(float px, float py...)
But inside these I would need Variant A or B again I guess.
Is it just a matter of taste or are there benefits for either?
I also have something like this
typedef struct {
int x;
int y;
Texture *texture;
bool walkable;
} Tile;
typedef struct {
int width;
int height;
Tile *tiles;
} Map;
Here a create function seems more reasonable, because I can pass actual map data.
mallocthenPlayer *createPlayer(float px, float py...)is good. If you use a localstructthenPlayer createPlayer(float px, float py...)is good. It might depend on what you want to do with eachPlayer. If you want several references to the same player (for example in a team, in a performance profile, etc) I would go the pointer route, rather than replicate thestructfor each.