我已经开始 C 编程大约 5 天了,但我在理解代码中到底发生了什么时遇到了一些困难。我在堆上填充了一个房间结构数组,每个房间都有整数值,我在分配空间后立即用用户输入填充。每个房间结构内都有一系列生物结构。我用来自 stdin 的 int 值填充每个房间内的字段,但是在填充它们并离开 for 循环后,这些值似乎会重置,并且我会在其位置获得随机值,类似于我事先在堆上分配内存时的情况。为什么我如此困惑是,当我用标准输入中的值填充我的生物数组时,我几乎在同一过程中进行操作,一切看起来都很好,并且可以在游戏中需要的地方访问这些值。非常感谢任何帮助,谢谢!我用于填充房间和生物的代码如下。
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) )
关于c - 在C中离开for循环后丢失结构数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25753571/