2014-09-05 109 views
0

我正在創建一個以前是面向對象的程序到同一個程序中,但是用C語言編寫,我沒有任何經驗,但我的學習速度很慢。我的問題是圍繞着我的第一步,那就是要有一堆我稱之爲堆的房間的結構。以及屁股填充陣列結構內的生物,從一個房間移動到另一個房間。到目前爲止,我的問題是試圖用從stdin讀入的信息填充房間變量。首先房間的數量(我的數組的大小),然後是狀態(乾淨或骯髒)以及房間是否有鄰居(一旦我可以先填充數組,那麼有條件的房間中將會連接有鄰居的房間)但這些都是整數。我以前給過的建議是讓全局指針指向數組,並在掃描時添加信息。我相信我可能會接近?但是無論我嘗試什麼,我都會在掃描完5個整數後立即得到分段錯誤。我對此非常陌生,並且儘快爲我的項目即將到期的日期進行學習。任何建議或幫助所有將不勝感激。我的代碼如下填充結構數組並在堆上分配內存

#include <stdio.h> 
#include <stdlib.h> 
typedef struct { 
int type; 
int room_number; 
int creat_number; 
} creature; 

struct room; 

typedef struct { 
struct room *north; //refernce to neighbor 
struct room *south; 
struct room *east; 
struct room *west; 
int room_name, state; 
creature creature_array[100]; 
} room; 
room *ptr; 
int respect = 40; 

int main(void) { 
int room_name, state, north, south, east, west; 
printf("Welcome!\n"); 
printf("How many rooms?\n"); 
int num_r; 
scanf("%d", &num_r); 
ptr = malloc(num_r * sizeof (room)); 
int i = 0; 
for (; i < num_r; i++) { 
    scanf("%d", "%d", "%d", "%d", "%d", &state, &north, &south, &east, &west); 
    (ptr + i)->room_name = i; 
    (ptr + i)->state = state; 
    (ptr+i)->north=north; 
    (ptr+i)->south=south; 
    (ptr+i)->east=east; 
    (ptr+i)->west=west; 
    if (north != -1) { 

    } 
    if (south != -1) { 

    } 
    if (east != -1) { 

    } 
    if (west != -1) { 

    } 

} 
+0

'scanf(「%d」,「%d」,「%d」,「%d」,「%d」,&state,&north,&south,&east,&west);'呃,不行,請閱讀'scanf'。 – 2014-09-05 13:37:53

+2

以及** ass **填充結構體內的數組? – Igor 2014-09-05 13:39:06

+0

我的目標是在我的下一步@Igor – Branbron 2014-09-05 13:45:03

回答

1

只有第一 scanf函數的參數被用作「格式」,這意味着你的

scanf("%d", "%d", "%d", "%d", "%d", &state, &north, &south, &east, &west); 

被解釋爲「爲格式"%d"獲得第一個參數,並解釋是作爲INT」。所以你的第二個"%d"被解釋爲int(因爲它是作爲它編譯的字符串數組的指針傳遞的),其他參數是忽略

用途:

scanf("%d %d %d %d %d", &state, &north, &south, &east, &west); 

而且建立你的代碼打開了警告!這會捕捉到一些令人討厭的錯誤。

+0

中填充結構體內的數組,我修正了它完全錯過了,現在我明白了很多! – Branbron 2014-09-05 15:01:09

+0

然後接受我的回答 – zoska 2014-09-09 07:41:48

+0

我該怎麼做?我不熟悉這個網站我只用過它幾次 – Branbron 2014-09-09 13:13:15