Alcott
Alcott

Reputation: 18585

`void *` to other pointer

If I pass a void *vptr to a function which takes a other_type *ptr as its arg, will vptr be converted automatically to other_type *? Here is the code,

typedef struct A {
    //...
}A;

void bar(A *a)
{
    //do something with a
}

int main()
{
    A a = {..};
    void *vp = &a;
    bar(vp);  //will vp be converted to A*?
}

Is my code safe or correct?

Upvotes: 3

Views: 280

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75130

Yes, void* is implicitly convertible to any pointer type, and any pointer type is implicitly convertible to void*. This is why you do not need to (and should not) cast the return value of malloc, for example.

Upvotes: 5

Perry
Perry

Reputation: 4495

Your code will work. You can pass a void * to something expecting a struct A *. C is only weakly typed in this regard.

Upvotes: 3

Related Questions