几乎每次我跳回 C 项目时,我都会把它搞砸。尝试访问结构中的结构时出现段错误。假设我有以下(简化的)游戏结构:
struct vector {
float x;
float y;
};
struct ship {
struct vector *position;
};
struct game {
struct ship *ship;
} game;
还有一个初始化船的函数:
static void
create_ship(struct ship *ship)
{
ship = malloc(sizeof(struct ship));
ship->position = malloc(sizeof(struct vector));
ship->position->x = 10.0;
}
然后在 main() 中:
int main() {
create_ship(game.ship);
printf("%f\n", game.ship->position->x); // <-- SEGFAULT
}