As stated in the documentation of malloc
, that function requires one parameter which specifies the number of bytes to allocate.
Therefore, in order to allocate sufficient memory to represent a single node, you must pass the size of an object of type struct Node
to the function malloc
.
Although it may be possible for you to calculate this size manually, the easiest way to determine the size of an object of type struct Node
is to use the sizeof operator. That is why the expression sizeof(struct Node)
is being passed as a parameter to the function malloc
.
Using the expression sizeof(struct Node*)
instead of sizeof(struct Node)
as a parameter for malloc
would be wrong, as that would only allocate sufficient memory for a pointer, but you want to allocate sufficient memory for an object of type struct Node
(which is probably larger than a pointer).
In the line
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
the (struct Node*)
is a type cast. It converts the data type void *
returned by malloc
to a struct Node *
.
In this context, the *
means "pointer", not multiplication. If you are unfamiliar with the concept of pointers, then I suggest that you first learn the basics of the programming language C, before you attempt to understand this. For example, here is a list of books. I suggest that you buy one under the category "Beginner".
Note that in contrast to C++, in C, casting the result of malloc
is not necessary and generally discouraged. See the following question for further information:
Do I cast the result of malloc?