Is typecast required in malloc?

This question already has an answer here:

  • Do I cast the result of malloc? 27 answers

  • I assume you mean something like this:

    int *iptr = (int*)malloc(/* something */);

    And in C, you do not have to (and should not) cast the return pointer from malloc . It's a void * and in C, it is implicitly converted to another pointer type.

    int *iptr = malloc(/* something */);

    Is the preferred form.

    This does not apply to C++, which does not share the same void * implicit cast behavior.


    You should never cast the return value of malloc() , in C. Doing so is:

  • Unnecessary, since void * is compatible with any other pointer type (except function pointers, but that doesn't apply here).
  • Potentially dangerous, since it can hide an error (missing declaration of the function).
  • Cluttering, casts are long and often hard to read, so it just makes the code uglier.
  • So: there are no benefits, at least three drawbacks, and thus it should be avoided.


    You're not required to cast the return value of malloc . This is discussed further in the C FAQ: http://c-faq.com/malloc/cast.html and http://c-faq.com/malloc/mallocnocast.html .

    链接地址: http://www.djcxy.com/p/28422.html

    上一篇: 类型malloc C ++

    下一篇: malloc需要typecast吗?