Sunday, 18 February 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

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