Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An array of structures within a structure - what's the pointer type?

Tags:

c++

c

I have the following declaration in a file that gets generated by a perl script ( during compilation ):

 struct _gamedata
{

 short res_count;
 struct
 {
  void * resptr;
  short id;
  short type;
 } res_table[3];
}
_gamecoderes =
{
 3,
 {
  { &char_resource_ID_RES_welcome_object_ID,1002, 1001 },
  { &blah_resource_ID_RES_another_object_ID,1004, 1003 },
{ &char_resource_ID_RES_someting_object_ID,8019, 1001 },
 }
};

My problem is that struct _gamedata is generated during compile time and the number of items in res_table will vary. So I can't provide a type declaring the size of res_table in advance.

I need to parse an instance of this structure, originally I was doing this via a pointer to a char ( and not defining struct _gamedata as a type. But I am defining res_table.

e.g.

char * pb = (char *)_gamecoderes; 
                           // i.e. pb points to the instance of `struct _gamedata`.
short res_count = (short *)pb;
pb+=2;
res_table * entry = (res_table *)pb;
for( int i = 0; i < res_count; i++ )
{
    do_something_with_entry(*entry);
}

I'm getting wierd results with this. I'm not sure how to declare a type _struct gamedata as I need to be able to handle a variable length for res_table at compile time.

like image 970
BeeBand Avatar asked Dec 10 '22 13:12

BeeBand


1 Answers

Since the struct is anonymous, there's no way to refer to the type of this struct. (res_table is just the member name, not the type's name). You should provide a name for the struct:

struct GameResult {
        short type;
        short id;
        void* resptr;
};

struct _gamedata {
        short res_count;
        GameResult res_table[3];
};

Also, you shouldn't cast the data to a char*. The res_count and entry's can be extracted using the -> operator. This way the member offsets can be computed correctly.

_gamedata* data = ...;
short res_count = data->res_count;
GameResult* entry = data->res_table;

or simply:

_gamedata* data;
for (int i = 0; i < data->res_count; ++ i)
   do_something_with_entry(data->res_table[i]);
like image 98
kennytm Avatar answered Apr 20 '23 01:04

kennytm