Reputation: 944
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* ??
Upvotes: 0
Views: 561
Reputation: 4045
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
.
Upvotes: 2
Reputation: 16607
. 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.
Upvotes: 1
Reputation: 227628
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
.
Upvotes: 1
Reputation: 91159
a -> b
is shorthand for (*a).b
.
If a
is not a pointer, *a
is not valid, and neither is a -> b
.
Upvotes: 3