繁体   English   中英

为嵌套结构分配内存,segfault

[英]Allocating memory for nested structure, segfault

所以,我正在努力为我的班级制作地图,我正在练习自己尝试实施一个嵌套循环,看看我是否采取“纽约---- 250公里------洛杉矶”有点道路,我应该是能够将NewYork作为以前的城市名称,将LosAngeles作为下一个城市名称。 距离是250公里。 我正在为城市名称,道路和城市记忆,但在我从键盘输入“next_city”部分后,我得到了段错误。 有人可以帮我解决我做错了什么吗?

typedef struct road road;
typedef struct city city;

struct city{
    int visited;
    int distance;
    int path;
    char *city_name;

};

struct road{
    int km;
    struct city *next_city, *previous_city;
};

int main()
{  

    char *a=malloc(sizeof(char)*10);
    char *b=malloc(sizeof(char)*10);

    city *NewYork = malloc(sizeof(city));
    NewYork->city_name = fgets(a,10,stdin); //this gives no error

    road *ROAD = malloc(sizeof(road));
    city *next_city = malloc(sizeof(city)); //to see if I can get a memory for LosAngeles

    ROAD->next_city->city_name = fgets(b,10,stdin); //but here it gives a segfault after I type the name to terminal..

}

那是因为ROAD->next_city没有指向有效地址,它是一个悬空指针。

请尝试以下方法:

road *ROAD = malloc(sizeof(road));
city *next_city = malloc(sizeof(city));
ROAD->next_city = next_city; 

这是你原本打算做的吗?

另请注意,您应该free通过malloc获取的malloc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM