Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer inside round brackets

void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node =
            (struct node*) malloc(sizeof(struct node));

    /* put in the data  */
    new_node->data  = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);   

    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

If i remember correctly, putting a brackets on a pointer means calling a function? If that's true i don't really understand why there are brackets on *head_ref. Id love a little explanation on why do i need brackets on *head_ref in this code.

like image 379
Segev Avatar asked Jan 15 '23 18:01

Segev


1 Answers

In this particular case, the brackets are serving no purpose other than to clarify the programmer's intent, i.e. they they want to dereference head_ref.

Note that head_ref is a pointer to a pointer, so in this case, new_node->next is being set to point to the original head of the linked list, and then the pointer pointed to by head_ref is being updated to point to new_node which is now the start of the list.

As Michael Krelin has pointed out below, putting brackets around a pointer do not mean it's a calling a function, or a pointer to a function. If you saw this: (*head_ref)() then it would be a call to the function pointed to by head_ref.

like image 166
Matt Lacey Avatar answered Jan 24 '23 17:01

Matt Lacey