我正在将以前的面向对象程序创建到同一个程序中,但用C编写,我没有任何经验,但学习缓慢。我的问题围绕着我的第一步,那就是在堆上有一个我称之为房间的结构数组。以及在结构内部的数组中填充从一个房间移动到另一个房间的生物。到目前为止,我的问题是试图用从stdin读取的信息填充房间变量。首先是房间的数量(我的数组的大小),然后是状态(干净或脏),以及房间是否有邻居(一旦我可以首先填充数组,有邻居的房间将在条件语句中连接),但这些都是整数。之前有人建议我用全局指针指向数组,并在扫描时以这种方式添加信息。我相信我可能已经接近了?但是,无论我在做什么,我都会在扫描完5个int后立即出现分割错误。我对此非常陌生,并尽可能快地为即将到来的C项目到期日学习。任何建议或帮助都将不胜感激。我的代码低于
#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) {
}
}
只有scanf的第一个参数用作"format",这意味着
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);
还要在启用警告的情况下构建代码!这会导致一些严重的错误。