0

I am currently working on a text based game in C and I'm having a problem altering values when certain events happen. 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. This affects me later because I need to alter things like n_monsters within the struct rooms for the current room. However, when I modify it by doing 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. 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.

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.
3
  • You don't tell us what a rooms is. Is it a typedef-ed struct ? Commented Mar 16, 2012 at 6:44
  • 1
    that looks reasonable; does anything make you think that this isn't working? Commented Mar 16, 2012 at 6:45
  • I think you want c_room = &(room[3]); // to point to the 4 room if you have rooms *c_room; Commented Mar 16, 2012 at 6:50

1 Answer 1

1

Assuming that c_room is a plain struct and not a pointer then you are right.

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 B.a since they are assigned by value. They will be two different A, any modification to one of them won't be reflected on the other.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this was really helpful. Yea, I was a huge nuisance to go through and change all the "."'s for "->"'s but now it works perfectly! Thank you again.
Don't forget to use valgrind to check that you don't have memory leaks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.