Consider following program:
#include <iostream>
void f(void* a)
{
std::cout<<"(void*)fun is called\n";
std::cout<<*(int*)a<<'\n';
}
int main()
{
int a=9;
void* b=(int*)&a;
f(b);
return 0;
}
If I change the function call statement like this:
f(&b);
It still compiles fine & crashes at runtime. Why? What is the reason? Should I not get the compile time error? Because the correct way to call the function is f(b). right? Also, why it is allowed to pass NULL to a function whose parameter is of type (void*)?
Please correct me If I am missing something or understanding something incorrectly.
It still compiles fine & crashes at runtime. Why? What is the reason?
Because void* is a technique for removing all type-safety and type checking.
Should I not get the compile time error?
By using void* instead of the correct pointer type int*, you are expressly telling the compiler not to tell you if you are using a type incorrectly or in an undefined way.
Because the correct way to call the function is f(b). right?
That's where your function declaration and contents disagree.
std::cout<<"(void*)fun is called\n";
std::cout<<*(int*)a<<'\n';
The contents above imply that a pointer to int should be passed:
void f(void* a)
This declaration implies some pointer should be passed, and no other restrictions are made.
void* can capture any type of pointers, there is no exception to void**
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With