The code below is from the book Programming Interviews Exposed 4th, now, to fix this, there are two possible ways,
bool insertInFront( IntElement *head, int data ){
IntElement *newElem = malloc( sizeof(IntElement) );
if ( !newElem ) return false;
newElem->data = data;
newElem->next = head;
head = newElem; // Incorrect! Updates only the local head pointer
return true;
}
The first way is to give a pointer to pointer as is suggested and taken from the book again...
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = malloc( sizeof(IntElement) );
if ( !newElem ) return false;
newElem->data = data;
newElem->next = *head;
*head = newElem;
return true;
}
The second way is where I simply dereference the head to update it's value by assigning the value dereferenced from the newElem.
bool insertInFront( IntElement *head, int data ){
IntElement *newElem = malloc( sizeof(IntElement) );
if ( !newElem ) return false;
newElem->data = data;
newElem->next = head;
*head = *newElem; // <---------- check this line here!
return true;
}
my question is that is there any difference between doing it with pointer to pointer or simply updating the value pointed to, strictly in context to the use case of linked lists.