tmsimont
tmsimont

Reputation: 2711

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?

Upvotes: 3

Views: 7393

Answers (3)

finalsemester.co.in
finalsemester.co.in

Reputation: 177

Variable of type void * can hold address of any symbol. Assignment to this variable can be done directly but while dereferencing it needs to be type cast to the actual type. This is required to inform the compiler about how much memory bytes needs to be accessed while dereferencing. Data type is the one which tells the size of a variable.

int a = 10;
char b = 'c';
void *c = NULL;
c = &a;
printf("int is %d\n", *((int*)c));
c = &b;
printf("char is %c\n", *(char*)c));

In above example void pointer variable c stores address of int variable a at first. So while dereferencing void pointer c, its typecasted to int *. This informs the compiler to access 4 byte (size of int) to get the value. And then in second printf its typecasted to char *, this is to inform the compiler to access one byte (size of char) to get the value.

Upvotes: 2

barak manos
barak manos

Reputation: 30136

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);

Upvotes: 5

user4815162342
user4815162342

Reputation: 154866

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.

Upvotes: 2

Related Questions