Saturday, 17 March 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...