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

后端 未结 7 2180
闹比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 20:24

    To put it simply:

    If you have included stdlib.h, as you should have, then the cast does absolutely nothing, and should be removed. After all, you've specified the type already.

    If you have not, then the cast will cover up the error, which is bad.

    Never use that cast in C code.

    In C++, the cast is necessary, as C++ doesn't permit implicit conversion between void * and other pointer types. On the other hand, in C++ there are better things to use than malloc(), such as new, or container classes.

    Writing code that will compile in either is pointless. You should always know what language you're writing in, and writing in the subset forces you to use a construct that's inferior in either language. The C++ compilers I'm familiar with will compile C code as well, and there are explicit provisions in C++ to link easily with C code. If you do compile it as C++, the error message (without the cast) will point out your mistake.

    All the cast will do is cover up mistakes that can bite you elsewhere. It won't do anything useful. Don't do it.

    0 讨论(0)
提交回复
热议问题