For the C code below, compare the defintions of the int pointers a and b;
#include
#include
int main()
{
int *a=malloc(s
In C the cast is unnecessary. malloc returns a void*, and the C standard states:
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
Further, K&R2 says:
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. Unlike the pointer-to-pointer conversions discussed in Par.A.6.6, which generally require an explicit cast, pointers may be assigned to and from pointers of type void*, and may be compared with them.
A point may be made about C++ compatibility, as in C++ the cast is obligatory. However, IMHO this is hardly relevant, as idiomatic C++ calls for using new instead of malloc anyway.