Is it a better practice to typecast the pointer returned by malloc?

后端 未结 7 2201
闹比i
闹比i 2020-12-10 19:30

For the C code below, compare the defintions of the int pointers a and b;

#include 
#include 

int main()
{
  int *a=malloc(s         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 19:59

    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.

提交回复
热议问题