gpt4 book ai didi

c - 嵌套结构和指针

转载 作者:太空狗 更新时间:2023-10-29 15:49:06 24 4
gpt4 key购买 nike

每次我跳回 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
}

最佳答案

您正在按值传递 game.ship,因此在 create_ship 中,变量 ship 只是该指针的一个副本,它只是更改副本。当函数返回时,指向您 malloced 的指针会丢失,除了内存泄漏外,函数的效果在函数外部不可见。

您需要将指针传递给指针并通过它修改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;
}

create_ship(&game.ship);

或者也许更好的方法是按照 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;
}

game.ship = create_ship();

当然,不要忘记free

关于c - 嵌套结构和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12694902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com