I'm using the following code to push a new node at the front of the linked list. I have some doubts regarding some concepts.
void push(struct node **head, int data)
{
// create a new node
struct node *new_node;
new_node = malloc(sizeof(struct node));
// add data
new_node->data = data;
// add node to front of list
new_node->next = *head;
*head = new_node;
}
When I assign the value of
new_node
to*head
in*head = new_node
, and then return, does the pointernew_node
get destroyed, as it's an automatic variable?Should the memory pointer by
new_node
, assigned to it by themalloc
call still be legal to access afternew_node
is destroyed, as it's on the heap, and was never de-allocated?We're just using the
new_node
as a placeholder to store an address to some memory, and after we're done with the assignments and stuff, we let it go. Then should it matter thatnew_node
is of typestruct node
, for all pointers are just integers, and we're just using it to store a memory address. Where does the pointer type become relevant i.e. why do I have to declare the data type of the pointer to match the pointee's datatype?Can I just declare all pointers as integers and then explicitly typecast them before using, to match the pointee's datatype?