Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`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?

like image 454
Alcott Avatar asked Mar 07 '26 08:03

Alcott


1 Answers

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.

like image 182
Seth Carnegie Avatar answered Mar 10 '26 01:03

Seth Carnegie