I'm trying to understand the differences between C and C++ with regards to void pointers. the following compiles in C but not C++ (all compilations done with gcc/g++ -ansi -pedantic -Wall):
int* p = malloc(sizeof(int));
Because malloc
returns void*
, which C++ doesn't allow to assign to int*
while C does.
However, here:
void foo(void* vptr)
{
}
int main()
{
int* p = (int*) malloc(sizeof(int));
foo(p);
return 0;
}
Both C++ and C compile it with no complain. Why?
K&R2 say:
Any pointer to an object may be converted to type void * without loss of information. If the result is converted back to the original pointer type, the original pointer is recovered.
And this pretty sums all there is about void*
conversions in C. What does C++ standard dictate?