Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a void pointer in struct

Here is what I got ..

typedef struct SysInfo_P
{
    int some_P_int;
    char some_P_char[10];
    ...

} SysInfo_P;


typedef struct SysInfo_S
{
    int some_S_int;
    char some_S_char[10];
    ...

} SysInfo_S;


typedef struct Device
{
    struct SomeData *data;
    void *sysInfo;
    ...
} Device;

The idea is to have a base class Device, and cast its void pointer to the appropriate SysInfo_x class during allocation. I use void pointers all the time to provide versatility to common functions, but I can't seem to wrap my head around this ... perhaps it cannot be done.

Here is my futile attempt at casting it .. in my allocator.

self->sysInfo = (SysInfo_S *)malloc(sizeof(*self->properties->sysInfo));
memset(self->sysInfo, 0, sizeof(*self->properties->sysInfo));
like image 534
Scott Mercer Avatar asked Dec 30 '25 21:12

Scott Mercer


1 Answers

What you want is a union:

typedef struct Device
{
    struct SomeData *data;
    union {
        struct SysInfo_S s;
        struct SysInfo_P p;
    } sysInfo;
    ...
} Device;
like image 160
dbush Avatar answered Jan 02 '26 13:01

dbush