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.
CodePudding user response:
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
.
CodePudding user response:
The postfix operators have higher precedence than unary operators.
So the expression
*lst->next
is equivalent to
*( lst->next )
but the pointer lst
does not point to an object of the structure type. It points to another pointer. So this expression lst->next
results in undefined behavior.