You need to initialize the members of the structure after you allocate it with malloc
:
struct node {
int data;
struct node *next;
};
struct node *n1 = malloc(sizeof(struct node));
n1->data = 0;
n1->next = NULL;
If you want to initialize your structure in one step with default values, which can be handy if it is much larger, use a static structure with these defaut values:
struct node def_node = { 0, NULL };
struct node *n1 = malloc(sizeof(struct node));
*n1 = def_node;
Alternately, you can use the C99 syntax:
struct node *n1 = malloc(sizeof(struct node));
*n1 = (struct node){ 0, NULL };
As commented by Leushenko, you can shorten the initializer to { 0 }
for any structure to initialize all members to the appropriate zero for their type:
struct node *n1 = malloc(sizeof(struct node));
*n1 = (struct node){ 0 };