3 ms·
For those curious how to create the "virtual head" in C: struct entry { int value; entry * next; }; entry * head = NULL; void remove_entry(entry *
by rovolo 8y ago
For those curious how to create the "virtual head" in C:
struct entry { int value; entry * next; };
entry * head = NULL;
void remove_entry(entry *target) {
long offset = (long)&((entry*)0)->next;
entry * curr = (entry*)((long)&head - offset);
while (curr->next != target)
curr = curr->next;
curr->next = target->next;
}
But I'm not sure how portable that is. It is portable if the next pointer is the first member of the struct though. From 6.7.2.1.13 in the C99 standard:
>A pointer to a structure object, suitably converted, points to its initial member
struct entry { entry * next; int value; };
...
// virtual entry where &(curr->next) = &head
entry * curr = (entry*)&head;
Note that it's exactly the same logic as the grandparent since
*curr = curr->next
indirect = curr
*indirect = *curr
*indirect = curr->next
indirect = &(curr->next)
But, I think that the virtual head entry is an easier mental model.
C99 standard: http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf