Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
tmsimont Avatar asked Jan 28 '26 17:01

tmsimont


2 Answers

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);
like image 88
barak manos Avatar answered Jan 30 '26 11:01

barak manos


Your struct declaration says void *, and your question says void. A void pointer member is a pointer to any kind of data, which is cast to the correct pointer type according to conditions known at run-time.

A void member is an "incomplete type" error.

like image 33
user4815162342 Avatar answered Jan 30 '26 10:01

user4815162342



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!