Alex Rivera | Logout

Passing Void type parameter in C

Asked 2009-11-21T17:37:20.747
10

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 three types of possibilities. All three, however, do have a member variable named "Count".

When I try to compile the actual code I wrote in Eclipse, 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, why isn't this working?

Edit
Report

2 Answers

11

First, you are passing in a pointer to void, which is a valid approach for unknown types, but you need to be passing in pointers to your different object types.

C isn't a dynamic language so symbolic type information is largely deleted before run time so when you say that your three types all have a member Count this doesn't help with your function design.

The only way you can access Count is by casting your void* parameter to the correct pointer type before derefencing with -> or (*element).Count (i.e. not just .).

Unless you are relying on your types having a compatible layout (which is likely to be implementation dependent) you will also need to pass something that helps your function determine the correct cast to perform. At this point you may be better off with three seperate functions and better type safety.

answered 2009-11-21T17:43:22.327
1

Use a cast.

ClassName(element).count++

Also, your element.Count = element.Count++; line is redundant. You just need to do element.count++ (which increments the value by one).

answered 2009-11-21T17:46:41.493

Your Answer