0

I am learning about malloc function & I see this difference but I cannot understand it

What is the difference between

ptr = (*int) malloc(sizeof(int)*N)

and

ptr = malloc(sizeof(int)*N)
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    `ptr = (*int) malloc(sizeof(int)*N)` is invalid syntax (specifically `*int` part is) and emit compile error while `ptr= malloc(sizeof(int)*N)` doesn't. – MikeCAT Jul 23 '20 at 17:04
  • 1
    Casting the return of `malloc` has been discussed [once or twice before](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – ryyker Jul 23 '20 at 17:05
  • changing the tags makes answer almost off topic – 0___________ Jul 23 '20 at 17:12

1 Answers1

1

In C cast of the malloc is considered the bad practice.

C++ is more type strict and you need to cast if you want to assign pointer with pointer of other type. But I would rather avoid direct use of the malloc (and generally pointers) in the C++ program.

In both I would rather use object in the sizeof operator

ptr = malloc(sizeof(*ptr)*N);

0___________
  • 60,014
  • 4
  • 34
  • 74