I would suggest another change, i.e. function prototypes should look like
void insert(struct list **, int); void print(struct list **);
and the body must be modified accordingly. Since you made new memory allocations in the insert, and therefore you should not make a pass by value, but rather should pass to the address, then only it will work as intended.
In addition, in the print function, the loop end should be while (* head! = NULL) instead of while ((* head) β next! = NULL), otherwise it will skip the last node.
You should also save the first node to the tmp pointer after you first call the insert function and that the tmp pointer must be passed to the print function at the end. In the code, you pass a pointer to the last node, which is incorrect. So it should be.
int main() { struct list *mylist=NULL, *tmp = NULL; insert(&mylist, 10); tmp = mylist; insert(&mylist, 20); insert(&mylist, 30); insert(&mylist, 40); insert(&mylist, 50); insert(&mylist, 60); print(&tmp); return 0; }
source share