Saturday, March 17, 2018

c - pointer to malloc?




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


I don't understand the * here : ...(struct node*) malloc(siz...
First, the * belongs to node or malloc? what does it mean? how pointers got anything to do with the memory function malloc?
I'm really confused with the * location



Thanks


Answer




A type name in parenthesis (such as (struct node *)) in C is called a "cast". It's a way to alter the type of an expression into the named type, and is commonly used with pointers.



However, this is code that ignores the advice in Do I cast the result of malloc. The cast is not needed here, making this (in my opinion, and perhaps not very surprisingly if you've followed that link) rather bad code.



The best way to write this allocation is:



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


This mentions the type exactly once, drops the cast which can introduce errors and is both pointless and cumbersome to read, and avoids introducing brittleness when specifying how much memory to allocate. It's win, win win.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...