Franny K. Franny K. - 1 year ago 78
C Question

difference between (*head)->next and &(*head)->next in C [LINKED LIST]

typedef struct n {
int data;
struct n *next;

This function deletes all nodes with odd values (without freeing memory or additional variables) :

void deleteOdds (node **head) {

if (*head == NULL) {
while ((*head)->next) {

if ((*head)->data % 2 != 0) {
*head = (*head)->next;
} else head = &(*head)->next;


I understand the logic (and already have some assumptions), but I'm not sure how to explain the difference between

*head =(*head)->next;


head = &(*head)->next;

thanks in advance!

Answer Source

The key to understanding what's going on is to see what is being assigned in each case:

  • *head = (*head)->next; assigns to whatever head is pointing to, which is either the original head pointer, the pointer to which is passed to the function, or a next of some prior node. We modify what is pointed to, while the pointer stays the same. This amounts to deleting from the list (and creating a memory leak in the process).
  • head = &(*head)->next assigns to the head itself, i.e. it modifies the pointer, not the thing that it points to. This amounts to skipping ahead in the list, without modifying it.

Note: head is not the ideal name for the variable. Since the variable points to head pointer only until the first "skip", a better name for it would be current.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download