cstructvoid-pointers

What does it mean to have a void* member of a struct in C?


I don't understand what kind of property the mystery member is below:

typedef struct _myobject
{
    long number;
    void *mystery;
} t_myobject;

What kind of member is this void * member? How much memory does that take up? Where can I get more information about what that accomplishes, for instance, why would one use a void * member?


Solution

  • A void* variable is a "generic" pointer to an address in memory.

    The field mystery itself consumes sizeof(void*) bytes in memory, which is typically either 4 or 8, depending on your system (on the size of your virtual memory address space, to be more accurate). However, it may point to some other object which consumes a different amount of memory.

    A few usage examples:

    int var;
    char arr[10];
    t_myobject obj;
    
    obj.mystery = &var;
    obj.mystery = arr;
    obj.mystery = malloc(100);