Wednesday 20 November 2019

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






Possible Duplicate:
Do I cast the result of malloc?






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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...