繁体   English   中英

在C中离开for循环后,结构数组中的值丢失

[英]Losing values in struct array after leaving for loop in C

我大约要花5天的时间进行C编程,但在理解代码中到底发生了什么时遇到了一些麻烦。 我在堆上填充一个房间结构数组,每个房间都有整数值,在分配空间后立即用用户输​​入填充。 每个房间结构内都有一系列生物结构。 我用stdin的int值填充每个房间内的字段,但是在填充它们并保留for循环之后,这些值似乎会重置,并且在随机位置上获得随机值的方式与我在堆上预先分配内存时类似。 我之所以如此困惑,是因为当我用stdin中的值填充我的生物数组时,我几乎以相同的过程进行操作,一切看起来都很好,并且可以在游戏中需要的地方访问这些值。 任何帮助,万分感谢! 我的填充房间和生物的代码如下。

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);
      }
   }
}

线

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) )

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM