1
所以,我想爲我的類做一個地圖,我正在練習自己嘗試實現一個嵌套循環,看看我是否拿一個「NewYork ---- 250km ---- --LosAngeles「有點道,我應該能夠把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..
}
我該如何得到這個工作,我的大腦不能正常工作知道,所以你可以請更明確地解釋 – Karavana
@ user1128905你分配內存的結構'道路',但不是內部指針,你嘗試分配給。 –
@ user1128905此外,編程最好用清晰的頭部完成。你現在可以在2小時內寫出什麼,明天早上你可以在5分鐘內完成,當你的大腦正在運作:) –