Rahul Reddy
Rahul Reddy

Reputation: 13163

difference between *head and (*head) pointers in C

The following is a sample code, not the working one. I just want to know the difference between *head and (*head) in pointers in C.

int  insert(struct node **head, int data) {

      if(*head == NULL) {
        *head = malloc(sizeof(struct node));
        // what is the difference between (*head)->next and *head->next ?
        (*head)->next = NULL;
        (*head)->data = data;
    }

Upvotes: 3

Views: 1499

Answers (5)

Jim Balter
Jim Balter

Reputation: 16406

There's no difference between a+b and (a+b), but there's a big difference between a+b*c and (a+b)*c. It's the same with *head and (*head) ... (*head)->next uses the value of *head as a pointer, and accesses its next field. *head->next is equivalent to *(head->next) ... which isn't valid in your context, because head isn't a pointer to a struct node.

Upvotes: 2

simonc
simonc

Reputation: 42185

* has lower precedence than -> so

*head->next

would be equivalent to

*(head->next)

If you want to dereference head you need to place the dereference operator * inside brackets

(*head)->next

Upvotes: 7

Navnath Godse
Navnath Godse

Reputation: 2225

The difference is because of operator precedence of C.

-> has higher precedence than *


Execution

For *head->next

 *head->next  // head->next work first ... -> Precedence than *
      ^
 *(head->next) // *(head->next) ... Dereference on result of head->next 
 ^

For (*head)->next

 (*head)->next  // *head work first... () Precedence
    ^
 (*head)->next  // (*head)->next ... Member selection via pointer *head 
        ^

Upvotes: 0

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58281

-> has higher precedence over *(Dereference) operator so you need parenthesis () around *head to overwrite precedence. So Correct is (*head)->next as you head is pointer to pointer of struct.

*head->next same as *(head->next) That is wrong (give you compiler error, actually syntax error)

Upvotes: 0

Williham Totland
Williham Totland

Reputation: 29019

There's no difference.

Usually.

In this case however, it's used to overcome a problem with operator precedence: -> binds more tightly than *, so without the parentheses *head->next works out to the equivalent of *(head->next).

Since this is not what is desired, *head is parenthesised in order for the operations to happen in the correct order.

Upvotes: 0

Related Questions