繁体   English   中英

C中* head和(* head)指针之间的差异

[英]difference between *head and (*head) pointers in C

以下是示例代码,而不是工作代码。 我只是想知道C中指针中*head(*head)之间的区别。

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;
    }

*优先级低于-> so

*head->next

相当于

*(head->next)

如果要取消引用head ,则需要将取消引用操作符*放在括号内

(*head)->next

a + b和(a + b)之间没有区别,但a + b * c和(a + b)* c之间存在很大差异。 它与* head和(* head)相同......(* head) - > next使用* head的值作为指针,并访问其下一个字段。 * head-> next相当于*(head-> next)...在你的上下文中无效,因为head不是指向struct节点的指针。

不同之处在于C的运算符优先级

->优先级高于*


执行

对于*head->next

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

对于(*head)->next

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

->具有比* (Dereference)运算符更高的优先级 ,因此您需要*head周围括号 () 来覆盖优先级 所以正确是(*head)->next因为你的head是指向struct的指针。

*head->next*(head->next)相同*(head->next)这是错误的(给你编译错误,实际上是语法错误

没有区别。

通常。

然而,在这种情况下,它用于克服运算符优先级的问题: ->绑定比*更紧密,因此没有括号*head->next可以相当于*(head->next)

由于这不是所期望的, *head是括号,以便以正确的顺序进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM