Sunday 24 December 2017

casting - How to use cast and pointers with malloc and sizeof

I am confused about when to use a cast with malloc in C.
What is the difference between these 2 pieces of code (the code in question is the
function that initializes a linked
list):




1st Excerpt:



 struct QueueNode {

char content;
struct QueueNode* prev;
struct QueueNode*
next;
};

struct Queue{

struct
QueueNode* first;
struct QueueNode* last;
};



Initialisation of the
Queue:



Queue* queueCreate()
{
Queue* q = (Queue*) malloc(sizeof(Queue));
q->first =
NULL;

q->last = NULL;
return
q;


}



2nd
excerpt:



typedef struct Element
Element;
struct Element


{
int
number;
Element *next;

};

typedef
struct List List;
struct List
{

Element
*first;
};


Initialisation
of the Queue:



List
*initialisation()
{
List *l = malloc(sizeof(*l));
Element
*element = malloc(sizeof(*element));


if (l == NULL ||
element == NULL)
{

exit(EXIT_FAILURE);
}

element->number =
0;
element->next = NULL;
l->first =
element;


return l;


}


This is what I don't
understand:
why in the first excerpt do we use a cast
(Queue*):



 Queue* q = (Queue*)
malloc(sizeof(Queue));



while
in the 2nd excerpt, there is no cast but we pass a pointer (*l) to sizeof, and there's
no cast?



Liste *l =
malloc(sizeof(*l))


So
I guess the problem is when to use the cast and when to pass a pointer to the sizeof
function.



ps. I read some answers here on so
like this one href="https://stackoverflow.com/questions/4519834/using-malloc-and-sizeof-to-create-a-struct-on-the-heap">Using
malloc() and sizeof() to create a struct on the
heap




it's about c++ and it
says you have to add a cast. In C, does the cast depend on the type of
implementation?



Thank you for your
help

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...