简体   繁体   English

在不同结构中指向结构的指针。 C

[英]Pointer to struct within different struct. C

I am currently working on a text based game in C and I'm having a problem altering values when certain events happen. 我目前正在使用C语言开发基于文本的游戏,在某些事件发生时更改值时遇到问题。 Here is some of my data structure code: 这是我的一些数据结构代码:

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;

Now, I think my problem is that I currently have c_room (Current Room) as a rooms, instead of a pointer to a rooms. 现在,我想我的问题是我目前有c_room(当前房间)作为房间,而不是指向房间的指针。 This affects me later because I need to alter things like n_monsters within the struct rooms for the current room. 这会在以后影响我,因为我需要为当前房间更改struct房间中的n_monsters之类的东西。 However, when I modify it by doing p.c_rooms.n_monsters -= 1; 但是,当我通过执行p.c_rooms.n_monsters-= 1修改它时; I'm not sure it alters the actual value of n_monsters for the room that I should be referring to. 我不确定它是否会更改我应参考的房间的n_monsters的实际值。 I've tested this by leaving a room when n_monsters is 0, and then coming back to see that it's back at 1, the default value. 我已经通过在n_monsters为0时留出一个空间,然后返回到它恢复为默认值1的方式来进行测试。

So yea, how would I point to right room? 是的,我要如何指向正确的房间? Just: 只是:

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.

Assuming that c_room is a plain struct and not a pointer then you are right. 假设c_room是普通结构而不是指针,那么您是对的。

If you have 如果你有

struct A {
  int v;
};

struct B {
  struct A a;
}

A a;
a.v = 3;

B b;
b.a = a;

This will actually copy the content of a inside Ba since they are assigned by value. 内容这实际上复制aBa ,因为他们是由价值分配。 They will be two different A , any modification to one of them won't be reflected on the other. 它们将是两个不同的A ,对其中一个的任何修改都不会反映在另一个上。

In your situation I would do something like: 在您的情况下,我会做类似的事情:

struct Room {
  // whatever
}

struct Room rooms[MAX_ROOMS];

struct Player {
  struct Room *room;
}

Player p;
p.room = &rooms[index];

Now you will be able to correctly reference to room by p->room , it will be just a pointer to the actual room. 现在,您将能够通过p->room正确引用p->room ,它只是指向实际房间的指针。

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

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