Is the type cast necessary when using malloc in C? [duplicate]
Possible Duplicate:
开发者_如何学Python 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.
精彩评论