I've been learning C on learn-c.org
After covering the unit regarding typedef declarations and structs. They finished with what they called "a recursive definition of a linked list" I found fairly straightforward, except for what seems like a mismatched pointer....
typedef struct node{
int val;
struct node* next;
}node_t
// usage
node_t* head = NULL;
head = (node_t*) malloc(sizeof(node_t));
head->val = 1;
head->next = (node_t*) malloc(sizeof(node_t));
head->next->val = 2;
head->next->next = (node_t*) malloc(sizeof(node_t));
head->next->next->val = 3;
My understanding is, by supplying typedef struct node
, we are able to declare the node pointer next
within the structure.
My confusion occurs on line 11. We are dynamically allocating memory for our next node, but we cast the void pointer as a node_t
pointer, not a node
pointer -- despite that fact that head->next
is a (node*)
type. Why is this allowed? Is C simply just recasting to a (node*)
behind the scenes, and (node_t*)
is used for readability?