嵌套结构和指针 [英] nested structures and pointers

查看:201
本文介绍了嵌套结构和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是我跳回成C项目每次白痴这件事。试图结构中访问的结构时,我得到一个段错误。比方说,我有以下(简体)结构的游戏:

 结构向量{
    浮X;
    浮ÿ;
};船舶结构{
    结构向量*位置;
};结构游戏{
    结构船*船舶;
} 游戏;

和初始化船的函数:

 静态无效
create_ship(结构船*船舶)
{
    船=的malloc(sizeof的(结构舰));
    船舶─>位置=的malloc(sizeof的(结构向量));
    船舶─>位置 - &X的催化剂= 10.0;
}

然后向下在main():

  INT的main(){
    create_ship(game.ship);
    的printf(%F \\ N,game.ship->&位置 - GT; X); //< - 段错误
}


解决方案

您逝去的 game.ship 按价值计算,所以在 create_ship 变量只是该指针的副本,它只是改变了副本。当函数返回时,指针,你的malloc ED丢失和功能的效果并不外面可见,除了内存泄漏。

您需要将指针传递到指针,并修改 game.ship 通过

 静态无效
create_ship(结构舰舰**)
{
    *船=的malloc(sizeof的(结构舰));
    (*船) - >位置=的malloc(sizeof的(结构向量));
    (*船) - >&位置 - GT; X = 10.0;
}

  create_ship(安培; game.ship);

也许一个更好的办法是做约翰尼MOPP建议在评论中,从函数返回指针,而不是改变它的一个外:

 静态结构的船* create_ship()
{
    船舶结构* S =的malloc(sizeof的(结构舰));
    S-GT&;位置=的malloc(sizeof的(结构向量));
    S-GT&;&位置 - GT; X = 10.0;    返回S;
}

  game.ship = create_ship();

当然,你还有什么的malloc 版,不要忘了免费

I dork this up just about every time I jump back into a C project. I'm getting a segfault when attempting to access a structure within a structure. Let's say I have the following (simplified) structures for a game:

struct vector {
    float x;
    float y;
};

struct ship {
    struct vector *position;
};

struct game {
    struct ship *ship;
} game;

And a function to initialize the ship:

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

Then down in main():

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

解决方案

You are passing game.ship by value, so inside create_ship the variable ship is just a copy of that pointer, and it just changes the copy. When the function returns, the pointer to what you malloced is lost and the effects of the function are not visible outside it, except for the memory leak.

You need to pass a pointer to the pointer and modify game.ship through that:

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

And

create_ship(&game.ship);

Or perhaps a better way would be to do as Johnny Mopp suggests in the comments, return the pointer from the function instead of modifying one outside of it:

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;
}

And

game.ship = create_ship();

And of course, what you have malloced, don't forget to free.

这篇关于嵌套结构和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆