Here I have tried to create a linked list and create a function which adds any given number to the staring of the linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head=NULL;
void Add(int n){
head=(struct Node*)malloc(sizeof(struct Node));
head->data=n;
head->next=NULL;
return;
}
Now my doubt is, here we have defined head
to be a pointer variable of datatype struct Node
. In Add
function, we have assigned the address of new memory allocated to head
pointer variable.
But when we are writing head->data=n
, why are we not dereferencing head
first, since head
was a pointer variable, so it stores address, and to store variables like data, why shouldn't it be *head->data
? Similar for *head->next=NULL
.
CodePudding user response:
The operator ->
is already a dereferencing operator. head->data
is equivalent to (*head).data
.