【问题标题】:What is the difference in '->' between struct node and struct node*?struct node 和 struct node* 之间的“->”有什么区别?
【发布时间】:2015-09-24 05:44:51
【问题描述】:

我是指针的新手,并且有此代码用于合并排序的链表。在这里它声明了一个虚拟节点为struct node dummy;,并且虚拟节点的下一个节点为NULL,所以我们使用dummy.next = NULL;来设置它。

/* Link list node */
struct node
{
    int data;
    struct node* next;
};
struct node* SortedMerge(struct node* a, struct node* b) 
{
   /* a dummy first node to hang the result on */   
   struct node dummy;      

   /* tail points to the last result node  */
   struct node* tail = &dummy;  

   /* so tail->next is the place to add new nodes 
     to the result. */
   dummy.next = NULL;
//Code continues...
}

我知道如果是struct node *dummy;,我可以使用它 但我们不能在这里使用它,因为它不是指针节点。 所以我的问题是为什么dummy->next = NULL 不在这里工作? struct node 和 struct node* 有什么区别??

【问题讨论】:

  • Dummy 不是指针,所以-> 不起作用。 -> 仅用于指针。
  • 所以基本上你问指针和普通变量之间的区别?

标签: c pointers struct


【解决方案1】:

a -> b(*a).b 的简写。

如果a 不是指针,则*a 无效,a -> b 也无效。

【讨论】:

    【解决方案2】:

    dummy 不是指向结构的指针。它是结构变量本身。 您可以使用运算符 -> 取消引用结构的属性,前提是它是指向结构的指针。

    如果您使用的是 struct 变量,那么. 是可行的方法,dummy 就是这种情况。

    【讨论】:

      【解决方案3】:

      我知道如果是struct node *dummy;我可以使用它

      如果“它”是指struct node dummy;,那么答案是否定的。您不能像使用指向 node 的指针一样使用指向 node 的指针。

      所以我的问题是为什么dummy->next = NULL 在这里不起作用?

      因为dummynode,而不是指针,而运算符-> 如果是指针。表达式dummy->next(*dummy).next 具有相同的语义。

      【讨论】:

        【解决方案4】:

        。所以我的问题是为什么 dummy->next = NULL 在这里不起作用? struct node 和 struct node* 有什么区别?

        声明为struct node dummy;

        dummy->next=NULL 不起作用,因为 dummy 不是指向 struct 的指针。

        如果你这么写的话-

        struct node A;  // then A is a struct variable which can access struct members  using '.' operator
        

        还有这个-

        struct node* B; // then B is a pointer to struct node which can access struct member using '->`  or like this (*B).data=something.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          • 1970-01-01
          • 2017-04-07
          • 2014-06-17
          相关资源
          最近更新 更多