简体   繁体   中英

How to do a cast from void* to a c struct

I have this struct

typedef struct tournament_t
{
 Map players;
}*Tournament;

the Map Adt used in the struct is generic and uses this typedef for void*

/** Data element data type for map container */
typedef void *MapDataElement;

I want a Copy Function for the Tournament struct and it has to be with type MapDataElement so this is the function

MapDataElement tournamentCopy(MapDataElement tournament)
{
 //some code
 Tournament ptr = *(Tournament*)tournament;
    copy->players=mapCopy(ptr->players);
//some code
}

the problem is that no matter what i do ptr->players is always null when I tried to change the type that the function gets from MapDataElement to Tournament everything worked fine, However I am not allowed to change it so... any ideas?

You have pointer confusion. Use:

typedef struct tournament_t
{
    Map players;
}Tournament;


typedef struct mapdataelement_t
{
     // definition
} MapDataElement;

and now:

MapDataElement *tournamentCopy(MapDataElement *tournament)
{
    Tournament *ptr = (Tournament *)tournament;

The root of all your problems is trying to hide pointers behind typedefs which makes the code needlessly complex and unreadable - you are only creating a bunch of problems for yourself with this.

Simply do:

typedef struct 
{
  Map players;
} tournament_t;

I want a Copy Function for the Tournament struct and it has to be with type MapDataElement

Ok so make MapDataElement something that makes sense, void* probably does not. If you want it to be some sort of generic item container then typedef it as such:

typedef struct
{
  void* data;
  size_t size;
  // whatever makes sense to include here, an enum to list types perhaps?
} MapDataElement;

And finally, modern C allows you to do type safe, type-generic programming without dangerous void pointers:

#define something_copy(x) _Generic((x), \
  tournament_t: tournament_copy,        \
  thingie_t:    thingie_copy) (x)

This means that the function-like macro "something_copy" will call the relevant specific function based on the type passed. Or if you pass a wrong type not supported - a compiler error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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