Malloc syntax in C
c, linked-list, list, malloc, struct
Solution
The code is dynamically creating a `pointer` to a single type of `struct node`. In most versions of C, the `(struct node *)` cast is not needed, and some argue that it shouldn't be used. If you remove the cast, it will be a `void*`, which can be used for any type.
Therefore:
newnode = (struct node*)malloc(sizeof(struct node));
is roughly equivalent to:
newnode = malloc(sizeof(struct node));
See: Specifically, what's dangerous about casting the result of malloc?
Note 1: If you are using Visual Studio to write your C code, it will give you red underlining if you don't cast the result of `malloc`. However, the code will still compile.
Note 2: Using `malloc` in C++ code requires you to cast the result as shown in your example.
Problem
In the books I read that the syntax for malloc is malloc(sizeof(int)) but in one of doubly linked list program I see the following: ``` newnode=(struct node *)malloc(sizeof(struct node)) ``` What is (struct node*) doing here? What is this entire code doing? btw, the code for the struct in the program is as below. ``` struct node { char line[80]; struct node *next,*prev; }; struct node *start=NULL,*temp,*temp1,*temp2,*newnode; ``` Thank you