I am trying to implement a function makelinkedList
which accepts the number of nodes in the linked List and returns the address of . The function printlinkedList
prints the linked list.
I don't get a segmentation fault when I implement this code.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
typedef struct node linkedList;
void printlinkedList(linkedList** head){
linkedList* crawler = *head;
while(crawler!=NULL){
printf("%d -> ", crawler->data);
crawler= crawler->next;
}
printf("|NULL|\n");
}
linkedList* makelinkedList(int size){
linkedList* crawler = malloc(sizeof(linkedList));
crawler->data = --size;
crawler->next = NULL;
linkedList* head = crawler;
while(size > 0){
crawler->next = malloc(sizeof(linkedList));
crawler = crawler->next;
crawler->data = --size;
crawler->next = NULL;
}
printlinkedList(&head);
return head;
}
int main(void) {
// your code goes here
linkedList* node = (makelinkedList(5));
linkedList** head = &node;
printf("from main\n");
printlinkedList(head);
return 0;
}
OutPut of the code given above:
4 -> 3 -> 2 -> 1 -> 0 -> |NULL|
But when I try to return the address of head (&head) I get a segmentation fault. The code that results in the fault is given below:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
typedef struct node linkedList;
void printlinkedList(linkedList** head){
linkedList* crawler = *head;
while(crawler!=NULL){
printf("%d -> ", crawler->data);
crawler= crawler->next;
}
printf("|NULL|\n");
}
linkedList** makelinkedList(int size){
linkedList* crawler = malloc(sizeof(linkedList));
crawler->data = --size;
crawler->next = NULL;
linkedList* head = crawler;
while(size > 0){
crawler->next = malloc(sizeof(linkedList));
crawler = crawler->next;
crawler->data = --size;
crawler->next = NULL;
}
return &head;
}
int main(void) {
// your code goes here
linkedList** head = (makelinkedList(5));
printf("from main\n");
printlinkedList(head);
return 0;
}
Why can't I return the address of the head ?