Search code examples
cpointersundefined-behaviordereference

Derefrencing a double pointer to a list


this is the Node

typedef struct s_list
{
    void            *content;
    struct s_list   *next;
}               t_list;
void    ft_lstclear(t_list **lst, void (*del)(void*))
{
    t_list  *temp;

    while ((*lst) != NULL)
    {
        temp = (*lst)->next;
        del((*lst)->content);
        free(*lst);
        *lst = temp;
    }
}

why when I remove () from the function does not work

void    ft_lstclear(t_list **lst, void (*del)(void*))
{
    t_list  *temp;

    while (*lst != NULL)
    {
        temp = *lst->next;
        del(*lst->content);
        free(*lst);
        *lst = temp;
    }
} 

I am trying to Delete and free the given element and every successor of that element, using the function ’del’ and free(3). the pointer to the list must be set to NULL.


Solution

  • The issue here is 'operator precedence' (https://en.cppreference.com/w/cpp/language/operator_precedence).

    As you can see from the list, the -> has a higher evaluation priority than the *, meaning that the compiler will attempt to 'access the member of **' instead of first dereferencing the ** into a *.

    The braces tell the compiler to first dereference the ** into a * and then access the member property.

    It's a lot like in math, actually.

    The equation: 4 + 3 * 3 = 13, whereas (4 + 3) * 3 = 21.