1

I'm trying to understand why I sometimes see brackets containing a data type on the right hand side of an assignment operator in C.

Specifically I was trying to implement a linked list and because I'm still new to C I was using this to guide me.

I came across this line: struct node* link = (struct node*) malloc(sizeof(struct node));

It's part of the instertFirst function which, I guess, adds a new item to the head of the linked list.

Breaking this line down according to my current understanding it states: create a struct node pointer called link that points to a newly allocated chunk of memory that is the size of the node struct.

What exactly then is the purpose of (struct node*) ? My best guess is that it gives that newly allocated chunk of memory a type...?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 3
    That's a typecast. – Barmar Oct 20 '21 at 16:42
  • It's redundant with `malloc()` because it returns `void *`, which can be converted to any other pointer type without casting. But in general, `(typename)` converts values from one type to another. – Barmar Oct 20 '21 at 16:43
  • 1
    Related: [What exactly is a type cast in C/C++?](/questions/7558837/what-exactly-is-a-type-cast-in-c-c) – John Bollinger Oct 20 '21 at 16:49

1 Answers1

1

The function malloc returns a pointer of the type void * independent on for which object the memory is allocated.

In C a pointer of the type void * may be assigned to a pointer of any other object type.

So you could write

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

In C++ such an implicit conversion is prohibited. You need explicitly to cast the returned pointer of the type void * to the type struct node * like

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

In C as it was mentioned above such a casting is redundant and sometimes only used for self-documenting of the code.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335