Sunday, July 1, 2018

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...