我目前正在用 C 语言开发一个基于文本的游戏,当某些事件发生时,我在更改值时遇到问题。这是我的一些数据结构代码:
typedef struct player {
int maxhealth;
int curhealth;
int in_combat;
monster c_enemy;
char *class;
char *condition;
rooms c_room;
inventory i;
stats stats;
} player;
现在,我认为我的问题是我目前将 c_room (当前房间)作为房间,而不是指向房间的指针。这会影响我以后,因为我需要改变当前房间的结构房间中的 n_monsters 之类的东西。但是,当我通过 p.c_rooms.n_monsters -= 1; 修改它时我不确定它会改变我应该提到的房间的 n_monsters 的实际值。我对此进行了测试,方法是在 n_monsters 为 0 时离开一个房间,然后回来查看它又回到默认值 1。
那么是的,我如何指向正确的房间? 只是:
typedef struct player {
int maxhealth;
int curhealth;
int in_combat;
monster c_enemy;
char *class;
char *condition;
rooms *c_room; // Like this?
inventory i;
stats stats;
} player;
// And then the assignment would look like:
c_room = *rooms[3]; <- an array of rooms for the dungeon in the game.
最佳答案
假设 c_room
是一个普通结构体而不是指针,那么你是对的。
如果你有
struct A {
int v;
};
struct B {
struct A a;
}
A a;
a.v = 3;
B b;
b.a = a;
这实际上会将 a
的内容复制到 B.a
中,因为它们是按值分配的。它们将是两个不同的 A
,对其中一个的任何修改都不会反射(reflect)在另一个上。
在你的情况下我会做类似的事情:
struct Room {
// whatever
}
struct Room rooms[MAX_ROOMS];
struct Player {
struct Room *room;
}
Player p;
p.room = &rooms[index];
现在您将能够通过p->room
正确引用房间,它将只是指向实际房间的指针。
关于c - 指向不同结构内的结构的指针。 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9733025/