I'm trying to understand why I sometimes see brackets containing a data type on the right hand side of an assignment operator in C.
Specifically I was trying to implement a linked list and because I'm still new to C I was using this to guide me.
I came across this line: struct node* link = (struct node*) malloc(sizeof(struct node));
It's part of the instertFirst
function which, I guess, adds a new item to the head of the linked list.
Breaking this line down according to my current understanding it states: create a struct node
pointer called link
that points to a newly allocated chunk of memory that is the size of the node
struct.
What exactly then is the purpose of (struct node*)
? My best guess is that it gives that newly allocated chunk of memory a type...?
CodePudding user response:
The function malloc
returns a pointer of the type void *
independent on for which object the memory is allocated.
In C a pointer of the type void *
may be assigned to a pointer of any other object type.
So you could write
struct node* link = malloc(sizeof(struct node));
In C such an implicit conversion is prohibited. You need explicitly to cast the returned pointer of the type void *
to the type struct node *
like
struct node* link = (struct node*) malloc(sizeof(struct node));
In C as it was mentioned above such a casting is redundant and sometimes only used for self-documenting of the code.