Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to malloc?

Tags:

c

pointers

struct

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

like image 282
Segev Avatar asked Sep 14 '25 15:09

Segev


2 Answers

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.

like image 154
unwind Avatar answered Sep 17 '25 07:09

unwind


struct node     <= type
*new_node       <= pointer named new_node (of type struct node)
=               <= assignment
(struct node *) <= cast to pointer of type struct node
malloc(SIZE)    <= returns pointer of type void, thus needs cast
like image 45
jacekmigacz Avatar answered Sep 17 '25 07:09

jacekmigacz