Friday 19 January 2018

c - pointer to malloc?

itemprop="text">

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 href="https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...