Reputation: 13
I am struggling with understanding structs and pointers, and thus, struggling to understand examples of linked lists in both my textbook and online.
What does the following code mean:
(struct NODE *)malloc(sizeof(struct NODE));
Will someone please provide a detailed explanation?
I understand that something is being allocated memory (the size in bytes of struct NODE), however, I don't understand what
(struct NODE *)
means.
Upvotes: 1
Views: 204
Reputation: 58291
Function malloc()
returns address of allocated memory. Return type of malloc()
function is void*
(it don't know for which type of data you are allocating memory), to assign it to pointer of your structure type you typecasts it into required type. So in you expression (struct NODE *)
is typecast instruction:
(struct NODE *) malloc (sizeof(struct NODE));
^
| ^
Typecast | call of malloc function with argument = sizeof(struct NODE)
Generally, you should avoid typecast a returned value from malloc
/calloc
functions in C ( read this: Do I cast the result of malloc? )
In C syntax of typecast is:
(rhsdatatype) data;
rhsdatatype
should be in parenthesis before data
.
Sometime in programming you need typecast: for example.
int a = 2;
int b = 3;
double c = a / b;
This code outputs 0.0
because 2/3
both are integers to /
result will be int that is 0
, and you assigns to double variable c = 0
. (what you may not wants).
So here typecast is solution, new code is:
int a = 2;
int b = 3;
double c = (double)a / (double)b;
it outputs real number output that is: 0.666
.
Upvotes: 2
Reputation: 42215
malloc returns void*
. (struct NODE *)
is a cast of this to a pointer to NODE
.
This cast is not required in C. Use of it is often considered poor style since it can cause bugs if you forget to include <stdlib.h>
for a declaration of malloc
.
Upvotes: 1