Is the type cast necessary when using malloc in C?

Possible Duplicate:
Do I cast the result of malloc?

I just learned how to use the malloc function, and my teacher mentioned that it's necessary to make a type cast when passing the memory address to the pointer. For example, here's a code to get 16 new bytes allocated (4 ints) using malloc:

#include <stdlib.h>

int main(){
   int *p;
   p = (int *)malloc(4*sizeof(int));

   return 0;
}

My question: is the (int *) cast on the right side of the attribution necessary? After all p is already a pointer to ints, so the pointer arithmetic should work fine even without that cast.

Thanks


You only need the cast if you are using malloc in C++ code.

For C it's preferable to not use the cast as it is (a) unnecessary and (b) can mask problems that would otherwise be reported by the compiler.

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

上一篇: 为什么我必须从malloc投出结果?

下一篇: 在C中使用malloc时是否需要类型转换?