Sunday 9 June 2019

c - Should I explicitly cast malloc()'s return value?




I wanted to ask about the following case:



char *temp;
temp = malloc(10);


Since the return type of malloc is void*, will the pointer returned by the malloc be implicitly cast to char* type before being assigned to temp? What does the standard say in this regard?




If our pointer variable is some struct type for example:



struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));


If we allocate memory to temp without casting it to struct node* type, will it be implicitly cast to struct node* type or is it necessary to explicitly cast it to struct node* type?


Answer



A void pointer in C can be assigned to any pointer without an explicit cast.


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...