Parameters in C are passed by value, rather than passed by reference, that is, formal parameters are just copies of actual parameters. Maybe you can understand why the following function doesn't work:
void negate(int num)
{
num = -num; // Doesn't work
}
The reason why the posted code doesn't work is just similar. head = newnode;
only changes the value of formal parameter head
. After push()
returns, the value of actual parameters from the caller remain unmodified. Thus, for the caller, nothing happens(expect that a block of memory is malloc()
ed but not free()
ed).
To change the value of variables, you must pass their address to functions:
void push(struct node **head,int data)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = data;
newnode->next = head;
*head = newnode;
}
See also: How do I modify a pointer that has been passed into a function in C?