[英]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.