C 프로그래밍에 약 5 일이 걸리고 코드에서 정확히 무슨 일이 일어나고 있는지 이해하는 데 어려움을 겪고 있습니다. 힙에 룸 구조체의 배열을 채 웁니다. 각 공간에는 공간을 할당 한 직후에 사용자 입력으로 채울 정수 값이 있습니다. 각 룸 구조체 안에는 일련의 생명체 구조체가 있습니다. stdin의 int 값을 사용하여 각 방의 내부 필드를 채 웁니다. 그러나 채우고 for 루프를 끝내면 값이 재설정 된 것처럼 보이고 사전에 힙에 메모리를 할당 할 때와 마찬가지로 임의의 값을 가져옵니다. 왜 그렇게 혼란 스럽습니까? stdin의 값으로 creature_array를 채울 때 나는 거의 동일한 과정을 거치므로 모든 것이 잘 보이고 내 게임에서 필요한 곳에 값을 액세스 할 수 있습니다. 어떤 도움이라도 대단히 감사합니다! 객실과 생물을 채우는 코드는 다음과 같습니다.C에서 루프를 떠난 후 구조체 배열의 값을 잃음
if (ptr[rm].creature_array[i].type != (0||1||2))
은 동일합니다 :
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);
}
}
}
실제로 컴파일됩니까? 그 한 줄에 여분의 뭉치 같이 보입니다. – Almo
들여 쓰기가 도움이 될지라도 나는 그것을 보았습니다. (if, else, for, function). 그러나 나는 아직 전역 적으로 사용되는 것처럼 보이지만 매개 변수로 전달되어야하는'ptr'에 대한 정의를 아직 찾지 못했습니다. – polarysekt
엉뚱한 간격에 대해 사과드립니다. 전 세계적으로 선언 된 포인터가 있습니다 : room * ptr; – Branbron