# 结构初始化的C结构

``````typedef struct {
float x;
float y;
} Vectorf;

typedef struct {
Vectorf position;
Vectorf direction;
Vectorf velocity;
} Player;
``````

``````Vectorf position = {1.0f, 1.0f};
Vectorf direction = {1.0f, 0.0f};
Vectorf velocity = {0.0f, 0.0f};

Player player = {position, direction, velocity};
``````

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

``````Player *createPlayer(float px, float py...)
Player createPlayer(float px, float py...)
``````

``````typedef struct {
int x;
int y;
Texture *texture;
bool walkable;
} Tile;

typedef struct {
int width;
int height;
Tile *tiles;
} Map;
``````

`malloc`当将结构视为类并且希望使用干净的API创建，使用和销毁它们时，我也会使用我总是对函数使用前缀，对于每种对象类型，我总是具有create，init和free函数，如下所示：

``````typedef struct abc {
// lot's of members
} Abc;

Abc *abc_create(void);
int abc_init(Abc *abc); // always with default values
void abc_free(Abc *abc);

int abc_do_A(Abc *abc, int x);
int abc_do_B(Abc *abc, int y);
....
``````

``````Abc *abc_create(void)
{
Abc *abc = calloc(1, sizeof *abc);
if(abc == NULL)
return NULL;

if(abc_init(abc) == 1)
return abc;

free(abc);
return NULL;
}

int abc_init(Abc *abc)
{
if(abc == NULL)
return 0;

// initializations
...

return 1;
}

void abc_free(Abc *abc)
{
if(abc == NULL)
return;

// do free of other malloced
// members if present
free(abc);
}
``````

``````Abc *abc = abc_create(1, 2, 3);
if(abc == NULL)
{
error handling
}

abc_do_A(abc, 12);
abc_do_A(abc, 11);
...
abc_free(abc); // when not needed anymore
``````

0 条评论