I was implementing a linked list with 3 elements using structs. It was working fine before I introduced the function to calculate the number of elements in the linked list Linked_list. Following is the code for the program in C.
C
#include <stdlib.h>
#include <stdio.h>
struct node{
int data;
struct node* next;
};
struct node* Linked_list();
int Length();
int main()
{
int length;
Linked_list();
length = Length();
printf("%d", length);
}
struct node* Linked_list() {
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("%d %d", head->data, second->data);
}
int Length(struct node* head){
struct node* current = head;
int count = 0;
while(current!=NULL)
{
count++;
current = current->next;
}
return count;
}
You are declaring and calling
Length()as it had no parameterslength = Length();But when you define it it does have one parameter:
This is legal, but what happens is that the actual function doesn’t get a
headparameter to work with and that is why it crashes.You should return
headfromLinked_list()(which is not currently returning anything) and feed that toLength().And then on main:
There might be other problems though.