Passing Void type parameter in C

Adam Lee picture Adam Lee · Nov 21, 2009 · Viewed 30.2k times · Source

Hello there I am working on an assignment in C where I need to pass in an unknown type of parameter into a function.

For example suppose I have the following:

int changeCount(void* element)
{
    element.Count = element.Count++;

    return 1;

}

The reason why variable element is void is because there are 3 types of possibilities. All 3 however do have a member variable named "Count".

When I try to compile the actual code I wrote in Eclipese, I get the following error:

error: request for member ‘Count’ in something not a structure or union

I am guessing this is happening because the compiler doesn't know the type of "element" before hand. However I don't see why this isn't working.

Thanks for help!

Answer

Naveen picture Naveen · Nov 21, 2009

You need to cast the pointer to one of those 3 types and then use it. Something like:

MyType* p = (MyType*)element;
p->count++;

However, you need to be sure of the type of the object you are casting as casting an object to the wrong type can be dangerous.