0

I am making a C program, which needs to access a struct array in a struct.

The definition looks like below

struct def_world
{
    bool lock;
    char tilemap;
    def_tile tile[100][100];
struct def_tile
{
    bool lock;
    char kind;
    def_obj * obj;
    void * evt;
};
struct def_obj
{
    bool lock;
    int indexOfTable;
    bool frozen;
    char x,y;
    char kind;
    char face;
    char * msg;
    char * ip;
};

in the main function, I want to access world's tile[3][3]'s obj's face.

I initialize world as

def_world world={0,};

but the following lines make errors

world.tile[3][3].obj=newobj();//newobj() returns def_obj type

world.tile[3][3].obj->face;

any idea how to access obj's face?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
kim taeyun
  • 1,837
  • 2
  • 24
  • 49
  • Show the at least the declaration for `newobj()` it's important to know whether it returns a `def_obj` object or a `def_obj*` pointer to a `def_obj`. Actually, why not post a compilable example that produces the errors that you get - it shouldn't be much more than what you have right now, but it will eliminate the need for people to guess about typos (please use copy-n-paste - don't retype it in the SO edit box). – Michael Burr Aug 23 '11 at 09:10
  • Works fine for me using VS2010 (and reversing the declared order of structs). Also, this is C++ not C, there is no `bool` in C. Perhaps `newobj` is defined as `def_obj newobj ()` rather than `def_obj *newobj ()`? – Skizz Aug 23 '11 at 09:46
  • the thing is that my VS2010 says No Members available when I just finished the typing world.tile[3][3] something wrong? – kim taeyun Aug 23 '11 at 10:13
  • I solved the problem sorry;; the thing I confused is struct definition order. after change the order, it works nicely thanks Michael and Skizz – kim taeyun Aug 23 '11 at 10:18
  • Even though you've got a solution, could you edit the question to show the actual declarations? You have a missing `};` on the declaration of `struct def_world`, you're referring to types before they've been declared, and you're referring to `struct def_tile` as just `def_tile` (which is legal in C++ but not in C). – Keith Thompson Aug 23 '11 at 17:34

1 Answers1

1

Try these lines instead:

world.tile[3][3]->obj=newobj();//newobj() returns def_obj type

world.tile[3][3]->obj.face;

Explanation:
world.tile[3][3] is a def_tile. It's obj field isn't def_obj, but rather def_obj*. Therefore, to get the def_obj that it points to, you should use ->obj.
Inside def_obj, face is just a char, so you would access it with .face.

Eran Zimmerman Gonen
  • 4,375
  • 1
  • 19
  • 31