The function gets the pointer first by value. It means that the function deals with a copy of the value of the pointer first
void deletefromBeg(struct node *first){
struct node *temp;
temp = first;
first = first->next;
printf("%d",temp->data);
free(temp);
}
Changing a copy of the value does not influence on the original value stored in the pointer first.
The pointer first
defined in main and the parameter first
of the function are two-different objects. Within the function you are changing the parameter first
that was initialized by a copy of the value of the pointer first
defined in main.
You have two approaches.
Either you have to return the new value of the pointer obtained within the function and assign it to the pointer first in main like
struct node * deletefromBeg( struct node *first )
{
if ( first != NULL )
{
struct node *temp = first;
first = first->next;
free( temp );
}
return first;
}
And in main you call the function like
first = deletefromBeg( first );
Or you should pass the pointer first by reference. In C passing an object by reference means passing the object indirectly through a pointer to the object.
void deletefromBeg( struct node **first )
{
if ( *first != NULL )
{
struct node *temp = *first;
*first = ( *first )->next;
free( temp );
}
}
And in main the function is called like
deletefromBeg( &first );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…