Wednesday, 14 March 2018

c - is it necessary to type-cast malloc and calloc











I was googling to find out the reason for type-casting of malloc and calloc. But, i only found type-casting of malloc is not necessary since it return void pointer but, what about calloc. This is the same reason for calloc too ???



Now, if we move back to first point, about return value of malloc and calloc. Then, i found that, both are returning the allocated spaces. So, i'm little bit confused here. So, my questions are






  1. What is the return value of malloc and calloc


  2. Is it necessary to type-cast malloc and calloc. And why ?




Answer




What is the return value of malloc and calloc?




It is a pointer to void (void*).





Is it necessary to type-cast malloc and calloc. And why ?




No, because the conversion from a pointer to void to a pointer to object is implicit.




C11 (n1570), § 6.3.2.3 Pointers
A pointer to void may be converted to or from a pointer to any object type.





It is right for both malloc and calloc.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...