#include <stdio.h>
struct stu {
int roll;
struct stu *next;
} stu1;
int main() {
stu1.roll = 1;
struct stu *head = &stu1; // Question about this line
head->next = &stu1;
printf("Address of Head : %p, Head->Next : %p, Head->Data : %d\n",
&head, head->next, head->roll);
printf("\nAddress of stu : %p,Stu->Next : %p, Stu->Data : %d",
&stu1, stu1.next, stu1.roll);
return 0;
}
So the line where I have declared the head pointer to structure, when I assign it as struct stu * head = &stu1; it just runs fine the whole program runs fine, but when I write struct stu * head; or struct stu * head = NULL; the program says segmentation fault.
I don't understand like what's the difference in them and ig when using Linked List, I would have to assign head as Head->next = headnode not as Head = &Headnode.
If you try to dereference a null pointer or uninitialized pointer, you get undefined behavior. A segmentation fault is one possible result of this.
If you write:
Then
headdoesn't actually point to anything. Bear in mind thathead->nextis equivalent to(*head).next.