This is a follow on from this question - Delete node from singly linked list with tail pointer in C
I've attempted to implement node deletion using the offsetof() macro mentioned by the answerer and after a lot of debugging I found that I needed to cast my pointer to a char* in order to be able to increment or decrement by 1 byte instead of 1 whole unit. The relevant line is commented below as //(RELEVANT LINE)
Is this the correct way to go about achieve this with only one double pointer? Is there a better way, avoiding casting to char*? Have I missed some fundamental of pointer arithmetic and I just got lucky here that my code hasn't fallen over?
For reference offsetof(lrsll_node, next) is 8, sizeof(lrsll_node) is 16
typedef struct lrsll_node {
char *data;
struct lrsll_node *next;
} lrsll_node;
typedef struct lrsll_list {
lrsll_node *head;
lrsll_node *tail;
} lrsll_list;
lrsll_node *lrsll_delete(lrsll_list *list, char *data) {
lrsll_node **node = &list->head;
while (*node && strcmp((*node)->data, data) != 0) {
node = &(*node)->next;
}
if (*node == NULL)
return NULL;
lrsll_node *deleted = *node;
*node = deleted->next;
if (deleted == list->tail) {
//RELEVANT LINE
list->tail = (node == &list->head) ?
NULL : (lrsll_node*) ((char*)node - offsetof(lrsll_node, next));
}
return deleted;
};
offsetof. +1 \$\endgroup\$