4

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

Community
  • 1
  • 1
Daniel Scocco
  • 7,036
  • 13
  • 51
  • 78

1 Answers1

5

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.

Paul R
  • 208,748
  • 37
  • 389
  • 560