嵌套结构和指针

ben*_*ier 4 c pointers structure

几乎每次我跳回C项目时,我都会这么说.在尝试访问结构中的结构时,我遇到了段错误.假设我有一个游戏的以下(简化)结构:

struct vector {
    float x;
    float y;
};

struct ship {
    struct vector *position;
};

struct game {
    struct ship *ship;
} game;
Run Code Online (Sandbox Code Playgroud)

以及初始化船舶的功能:

static void
create_ship(struct ship *ship)
{
    ship = malloc(sizeof(struct ship));
    ship->position = malloc(sizeof(struct vector));
    ship->position->x = 10.0;
}
Run Code Online (Sandbox Code Playgroud)

然后在main()中:

int main() {
    create_ship(game.ship);
    printf("%f\n", game.ship->position->x); // <-- SEGFAULT
}
Run Code Online (Sandbox Code Playgroud)

Set*_*gie 9

您正在传递game.ship值,因此create_ship变量内部ship只是该指针的副本,它只是更改了副本.当函数返回malloc时,除了内存泄漏之外,指向你的内容的指针都会丢失,并且函数的效果在它之外是不可见的.

您需要传递指针指针并game.ship通过以下方式修改:

static void
create_ship(struct ship **ship)
{
    *ship = malloc(sizeof(struct ship));
    (*ship)->position = malloc(sizeof(struct vector));
    (*ship)->position->x = 10.0;
}
Run Code Online (Sandbox Code Playgroud)

create_ship(&game.ship);
Run Code Online (Sandbox Code Playgroud)

或者也许更好的方法是按照Johnny Mopp在评论中建议的那样,从函数返回指针而不是修改它之外的指针:

static struct ship* create_ship()
{
    struct ship* s = malloc(sizeof(struct ship));
    s->position = malloc(sizeof(struct vector));
    s->position->x = 10.0;

    return s;
}
Run Code Online (Sandbox Code Playgroud)

game.ship = create_ship();
Run Code Online (Sandbox Code Playgroud)

当然,你malloc所做的,不要忘记free.