(struct node*)
is cast, which is an explicit type conversion. The *
belongs to struct node
, stating that the type requested is a pointer to a struct node
variable. malloc() always returns a void*
, a void pointer.
The function definition of malloc is void* malloc (size_t size);
(and the *
belongs to void
in that case as well).
The person who wrote the code posted in your question casted this void pointer into a struct node*
. Why they did this isn't clear, they were either confused about how pointer casts in C work and also unaware of the dangers with such casts, or the code was written for C++.
A void pointer in the C language is a generic pointer type that can be converted to any other pointer type, without a cast (1).
In C++ however, you must always have a cast when converting a void pointer, because C++ has stricter type conversion rules than C and enforces an explicit conversion.
Casting the result of malloc() in C is dangerous and considered a bug (2), because unless the correct function prototype is provided through #include , then the compiler default behavior kicks in and it will incorrectly believe that malloc returns int. Depending on pointer and integer widths of the particular system, it may work just fine, or it may cause the program to crash and/or leak memory.
Casting the result of malloc() in C++ is however necessary.
References:
- ISO 9899:2011 6.3.2.3/1.
- Specifically, what's dangerous about casting the result of malloc?