当我在 ubuntu 13.04 的 gcc 编译器中运行以下 C 程序以创建链表时,我收到一条消息:Segmentation fault (core dumped),在从用户输入列表元素后,没有继续。请帮忙。
#include<stdio.h>
#include<stdlib.h>
int main()
{
/* creating a singly linked list,displaying its elements and finding the sum and average of its elements and searching a particular element in it */
typedef struct node
{
int info;
struct node *next;
}N;
N *ptr,*start,*prev;
int i,n,x;
ptr=NULL;
start=NULL;
prev=NULL;
printf("Enter the number of list elements: ");
scanf("%d",&n);
prev = (N*)malloc(sizeof(N));
start = (N*)malloc(sizeof(N));
for(i=0;i<n;i++)
{
ptr= (N*)malloc(sizeof(N));
prev->next = ptr;
printf("enter the %dth element\t\n",(i+1));
scanf("%d",&x);
ptr->info = x;
if(start==NULL)
{
start=ptr;
prev=ptr;
ptr->next = NULL;
}
else
{
prev=ptr;
}
} /* linked list created consisting of n nodes */
/* finding sum and average*/
int sum=0;
float avg;
ptr=start;
for(i=0;i<n;i++)
{
sum =sum + ptr->info;
ptr = ptr->next;
}
avg = (float)sum/n; /* summing and averaging completed */
/* displaying data */
ptr=start;
printf("\n The list elements are : ");
while(ptr != NULL)
printf("%d\t",ptr->info);
printf("\n");
printf("The sum of list elements is: %d",sum);
printf("The average of list elements is: %f",avg);
return 0;
}