pointers in C and use in linked list -


i struggling understanding structs , pointers, , thus, struggling understand examples of linked lists in both textbook , online.

what following code mean:

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

will please provide detailed explanation?

i understand being allocated memory (the size in bytes of struct node), however, don't understand what

(struct node *) 

means.

function malloc() returns address of allocated memory. return type of malloc() function void* (it don't know type of data allocating memory), assign pointer of structure type typecasts required type. in expression (struct node *) typecast instruction:

(struct node *) malloc (sizeof(struct node));      ^                    |             ^       typecast     | call of malloc function argument = sizeof(struct node) 

generally, should avoid typecast returned value malloc/calloc functions in c ( read this: do cast result of malloc? )

in c syntax of typecast is:

 (rhsdatatype) data; 

rhsdatatype should in parenthesis before data.

sometime in programming need typecast: example.

int = 2;  int b = 3;  double c = / b;  

this code outputs 0.0 because 2/3 both integers / result int 0, , assigns double variable c = 0. (what may not wants).

so here typecast solution, new code is:

int = 2;  int b = 3;  double c = (double)a / (double)b;  

it outputs real number output is: 0.666.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -