简体   繁体   中英

What is the difference in '->' between struct node and struct node*?

I am new to pointers and there is this code for merge sort of linked lists. And here it has declared a dummy node as struct node dummy; and the next node for dummy node is NULL so to set it we use 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...
}

I understand that i can use it if it was struct node *dummy; but we cant use it here as it is not a pointer node. So my question is why doesn't dummy->next = NULL work here? and what is the difference between struct node and struct node* ??

a -> b is shorthand for (*a).b .

If a is not a pointer, *a is not valid, and neither is a -> b .

dummy is not a pointer to a structure. It is the structure variable itself. You can derefer attributes of a structure with the operator -> only if it is a pointer to the structure.

If you are using the struct variable, then . is the way to go about, which is very much the case with dummy .

I understand that i can use it if it was struct node *dummy;

If by "it" you mean struct node dummy; then the answer is no. You cannot use a pointer to node in the same way as a pointer to node .

So my question is why doesn't dummy->next = NULL work here?

Because dummy is a node , not a pointer, and operator -> if for pointers. The expression dummy->next has the same semantics as (*dummy).next .

. So my question is why doesn't dummy->next = NULL work here? and what is the difference between struct node and struct node* ?

Declared as this struct node dummy;

dummy->next=NULL doesn't work because dummy is not a pointer to struct .

If you write so -

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

and this -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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