vendredi 31 juillet 2015

Segmentation fault in linked list creation

I wrote the following program to create a singly linked list. However it gives a segmentation fault at line 28: ptr->info =x; The program gets terminated here after inputting the first node of the linked list.

#include<stdio.h>
#include<stdlib.h>

int main(void)
{

struct node
{
    int info;
    struct node *link;
};

struct node *ptr,*start,*prev;
int n,x,i;

printf("enter the number of linked list elements\n");
scanf("%d",&n);
ptr=malloc(n*sizeof(struct node));
prev=malloc(n*sizeof(struct node));
start=malloc(n*sizeof(struct node));
ptr=NULL;
start=NULL;
prev=NULL;
for(i=0;i<n;i++)
{
    printf("enter the element\n");
    scanf("%d\n",&x);
    ptr->info =x;
    ptr->link =NULL;
    if(start==NULL)
    {
        prev=ptr;
        start=ptr;
    }
    else
    {
        prev->link = ptr;
        prev=ptr;
    }
}

ptr = start;
while(ptr != NULL)
{
    printf("%d ",ptr->info);
    ptr = ptr->link;
}
return 0;
}

What is the problem in the code?

Aucun commentaire:

Enregistrer un commentaire