在C中保留循环后丢失struct数组中的值

时间:2014-09-09 21:05:14

标签: c arrays pointers struct

我进入C编程大约需要5天,而且我在理解代码中究竟发生了什么方面有点麻烦。我在堆上填充了一系列房间结构,每个房间都有整数值,我在分配空间后立即填写了用户输入。每个房间结构中都有一系列生物结构。我使用来自stdin的int值填充每个房间内的字段,但是在我填充它们并离开for循环之后,值似乎重置并且我在其位置获得随机值,类似于我事先在堆上分配内存时。为什么我这么困惑的是,当我用stdin的值填充我的creature_array时,我几乎在同一个过程中完成它,一切看起来都很好,这些值可以在游戏中需要的地方访问。非常感谢任何帮助!我填写房间和生物的代码如下。

typedef struct {
   int type;
   int room_number;
   int creat_number;
} creature;

typedef struct {
   struct room *north; //refernce to neighbor
   struct room *south;
   struct room *east;
   struct room *west;
   int n,s,e,w;
   int room_name, state;
   creature creature_array[10];
} room; 

void addCreature(int rm, int t, int cm) {
   int i = 0;
   int f = 0;
  for (; i < 10; i++) {
      if (ptr[rm].creature_array[i].type != 0 && ptr[rm].creature_array[i].type != 1 && ptr[rm].creature_array[i].type !=2) {
         ptr[rm].creature_array[i].creat_number = cm;
         ptr[rm].creature_array[i].type = t;
         ptr[rm].creature_array[i].room_number = rm;
         break;
      } else {
         f++;
         if (f == 9) {
            printf("Room ");
            printf("%d", ptr[rm].room_name);
            printf(" is full.\n");
         }
       }
     }
   }

int main(void) {
   setbuf(stdout, NULL);
   int state, north, south, east, west;
   printf("Welcome!\nHow many rooms?\n");
   int num_r;
   scanf("%d", &num_r);
   ptr = (room *)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].n=north;
      ptr[i].s=south;
      ptr[i].e=east;
      ptr[i].w=west;
   }
   printf("How many creatures?\n");
   int room_num, type, creat_num;
   int num_of_c;
   scanf("%d", &num_of_c);
   int p = 0;
   int PC_count = 0;
   int creat_count = 0;
 for (; p < num_of_c; p++) {
      creat_num = creat_count++;
      scanf("%d %d", &type, &room_num);
      if (type == 0) {
         PC_count++;
         if (PC_count > 1) {
            printf("Too many PC players\n");
            exit(0);
         }
         addCreature(room_num,type,creat_num);
         pc = &ptr[room_num].creature_array[p];
      } else {
         addCreature(room_num,type,creat_num);
      }
   }
}

2 个答案:

答案 0 :(得分:0)

该行

if (ptr[rm].creature_array[i].type != 0||1||2)

相当于:

if (ptr[rm].creature_array[i].type != (0||1||2) )

相当于:

if (ptr[rm].creature_array[i].type != 1 )

这就是你想要的吗?

我怀疑你想要:

if ( (ptr[rm].creature_array[i].type != 0) &&
     (ptr[rm].creature_array[i].type != 1) &&
     (ptr[rm].creature_array[i].type != 2) )

答案 1 :(得分:0)

addCreature()使用未初始化的ptr[room_num].creature_array值。