【发布时间】:2012-09-23 13:53:28
【问题描述】:
我几乎每次跳回 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
}
【问题讨论】:
-
作为旁注,您可以使用
typedef struct {float x; float y;} vector;之类的内容,因此您不必每次使用该类型时都说struct。