1

I have problem understanding implementation of linked lists, I get basic idea, but I have one question:

new_node = (node*) malloc(sizeof(node))

Why do we use here (node*)? Why don't we just say:

new_node = malloc(sizeof(node))?

Thanks for the answer in advance.

typedef struct node{
 int value;
 struct node* next_node;
}node;

node* create_node(int v){
 node* new_node;

 new_node=(node*) malloc(sizeof(node));
 if(new_node==NULL){
    fprintf(stderr, "Allocation problem.\n");
    exit(1);
 }
 new_node->value=v;
 new_node->next_node=NULL;

 return new_node;
}
Xan
  • 74,770
  • 16
  • 179
  • 206
Aleksandar Makragić
  • 1,957
  • 17
  • 32
  • As an aside, the article also explains why `sizeof(node_type)` is a bad idea, and what should be used instead. In addition, I prefer `!new_node` to `new_node == NULL`... – Deduplicator Jan 19 '15 at 16:21

1 Answers1

2

The return type of malloc () is a void pointer.

This void pointer is safely promoted to the struct type without any casting.

So you do not need to cast the result of malloc().

But it is a good coding practice to include the cast. You can read the detailed answer here. Corrections: @UnderDog

Community
  • 1
  • 1
sumithdev
  • 331
  • 1
  • 8