2014-09-05 106 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