I was writing a function which removes a node in a linked list, whose input is a pointer to a linked list. If the function removes a linked list that has only one node, the function will make the pointer point to NULL. Here’s part of the code:
void remove(dlinkNode_t *start){
//some previous code
if(start->next==NULL){//meaning we're removing the head of the linked list
dlinkNode_t current=start; //get a temp pointer to point at this node
start=NULL; //make start point to null
free(current); //free the head
return;
}
// More code
In main I created a linked list with one node, and passed this linked list to remove function to free it. Here’s the code:
int main(){
dlinkNode_t *node1=create(); //creates a node and make node1 point at it
remove(node1); //now node1 should point at NULL
if(node1==NULL)
printf("hi");
return 0;
}
But I didn’t see the hi printed. I don’t know why the if statement didn’t pass. Any ideas?
A new copy of the pointer is made in the local scope of
remove. Any changes you make to the pointer will only be visible in that scope. Any changes that you make to the value being pointed to by a pointer will return to the calling scope.You can solve this problem in one of two ways :
Return the edited pointer
and make the change in remove as well.
Or you can pass a pointer to the pointer start and then manipulate that pointer.
Function call :
Function definition :