hi every1,
im kind of new to programming and i have a question about lists. i found a pretty neatly done code from this site
The C Programming Language
Ron Wein's C Examples: list.c
for doubly linked lists.
in his code ron defines an element structure which will be used to append data into the doubly linked list, it contains a struct element *prev, struct element *next, and data .
in his append function here is what he writes
Code:
/* ------------------------------------------------------------------------
* Function: list_append
*/
void list_append (List *p_list, double x)
{
Element *p_elem;
/* Sanity check: */
if (p_list == NULL)
exit(-1);
/* Allocate a new Element object and set its fields. */
p_elem = (Element *) malloc (sizeof(Element));
p_elem->value = x;
p_elem->p_prev = NULL;
p_elem->p_next = NULL;
/* Set the element as the new list tail. */
if (p_list->p_tail != NULL)
{
/* The new element should be placed after the current list tail. */
p_list->p_tail->p_next = p_elem;
p_elem->p_prev = p_list->p_tail;
/* Set the new element as the new list tail. */
p_list->p_tail = p_elem;
}
else
{
/* The list is empty - the new element should be both its head and
its tail. */
p_list->p_head = p_elem;
p_list->p_tail = p_elem;
}
/* Increment the list size. */
p_list->size++;
return;
}
here is my question.
in the line where it says
p_elem = (Element *) malloc (sizeof(Element));
whats the purpose for declaring a pointer to struct Element, and afterwards allocating the struct size.
i am aware of the need to allocate the memory for then data can be written to it, but what i dont understand is the need for the (Element *). what will this do to p_elem, how is it relevant for the list?
is the p_elem pointer already set by the