0

当我在 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;
}
4

2 回答 2

1

看起来你打算这样做

    start = NULL; 
    prev = NULL;

一开始,也是正确的-

  prev->next = ptr;

  if (prev != NULL)
      prev->next = ptr;

或将其移至 else 部分(在 prev = ptr 之前)。

这样,第一次迭代将使起点指向第一个元素,下一次迭代将使 prev 元素指向当前 ptr。

顺便说一句,一些链表包含一个虚拟的“锚”元素以便于维护,但在你的情况下,我看到你希望数据已经从第一个元素出现。

于 2013-09-09T10:20:38.473 回答
0

当我剥离你的代码时,我来到了这个 Seltsamkeit:

start = (N*)malloc(sizeof(N));                                     

for(i=0;i<n;i++) {
   if(start==NULL)

在这种情况下 start 永远不能为 NULL

我通常使用“head”和“next”作为指向工作内存的指针,“list”作为指向真正分配的内存链表的最后一个元素的运行指针。元代码是:

list = NULL;
head = NULL;
for (i = 0; i < n; i++) {
  next = malloc();
  if (head == NULL) {
    head = next; // setting the first haed;
  } else {
    list->next = next; // attaching to the end
  }
  list = next; // pointing to the last element
}
于 2013-09-09T10:11:50.737 回答